diff --git a/application/src/main/java/org/thingsboard/server/controller/DeviceController.java b/application/src/main/java/org/thingsboard/server/controller/DeviceController.java index e2db45884f..68a016bf4e 100644 --- a/application/src/main/java/org/thingsboard/server/controller/DeviceController.java +++ b/application/src/main/java/org/thingsboard/server/controller/DeviceController.java @@ -278,7 +278,6 @@ public class DeviceController extends BaseController { try { Device device = checkDeviceId(deviceCredentials.getDeviceId(), Operation.WRITE_CREDENTIALS); DeviceCredentials result = checkNotNull(deviceCredentialsService.updateDeviceCredentials(getCurrentUser().getTenantId(), deviceCredentials)); - //log.info("0 LwM2M CredentialsUpdate start) tbClusterService.pushMsgToCore(new DeviceCredentialsUpdateNotificationMsg(getCurrentUser().getTenantId(), deviceCredentials.getDeviceId(), result), null); logEntityAction(device.getId(), device, device.getCustomerId(), diff --git a/application/src/main/java/org/thingsboard/server/controller/DeviceLwm2mController.java b/application/src/main/java/org/thingsboard/server/controller/DeviceLwm2mController.java index 76915fbed1..4ddeff5af6 100644 --- a/application/src/main/java/org/thingsboard/server/controller/DeviceLwm2mController.java +++ b/application/src/main/java/org/thingsboard/server/controller/DeviceLwm2mController.java @@ -15,17 +15,32 @@ */ package org.thingsboard.server.controller; +import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.thingsboard.rule.engine.api.msg.DeviceNameOrTypeUpdateMsg; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.lwm2m.LwM2mObject; import org.thingsboard.server.common.data.lwm2m.ServerSecurityConfig; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; +import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.security.permission.Resource; import java.util.List; +import java.util.Map; @Slf4j @RestController @@ -33,13 +48,16 @@ import java.util.List; @RequestMapping("/api") public class DeviceLwm2mController extends BaseController { - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") - @RequestMapping(value = "/lwm2m/deviceProfile/{objectIds}", method = RequestMethod.GET) + @RequestMapping(value = "/lwm2m/deviceProfile", params = {"sortOrder", "sortProperty"}, method = RequestMethod.GET) @ResponseBody - public List getLwm2mListObjects(@PathVariable("objectIds") int[] objectIds) throws ThingsboardException { + public List getLwm2mListObjects(@RequestParam String sortOrder, + @RequestParam String sortProperty, + @RequestParam(required = false) int[] objectIds, + @RequestParam(required = false) String searchText) + throws ThingsboardException { try { - return lwM2MModelsRepository.getLwm2mObjects(objectIds, null); + return lwM2MModelsRepository.getLwm2mObjects(objectIds, searchText, sortProperty, sortOrder); } catch (Exception e) { throw handleException(e); } @@ -50,11 +68,11 @@ public class DeviceLwm2mController extends BaseController { @ResponseBody public PageData getLwm2mListObjects(@RequestParam int pageSize, @RequestParam int page, - @RequestParam(required = false) String textSearch, + @RequestParam(required = false) String searchText, @RequestParam(required = false) String sortProperty, @RequestParam(required = false) String sortOrder) throws ThingsboardException { try { - PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); + PageLink pageLink = createPageLink(pageSize, page, searchText, sortProperty, sortOrder); return checkNotNull(lwM2MModelsRepository.findDeviceLwm2mObjects(getTenantId(), pageLink)); } catch (Exception e) { throw handleException(e); @@ -72,4 +90,40 @@ public class DeviceLwm2mController extends BaseController { throw handleException(e); } } + + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") + @RequestMapping(value = "/lwm2m/device-credentials", method = RequestMethod.POST) + @ResponseBody + public Device saveDeviceWithCredentials(@RequestBody (required=false) Map, Object> deviceWithDeviceCredentials) throws ThingsboardException { + ObjectMapper mapper = new ObjectMapper(); + Device device = checkNotNull(mapper.convertValue(deviceWithDeviceCredentials.get(Device.class), Device.class)); + DeviceCredentials credentials = checkNotNull(mapper.convertValue( deviceWithDeviceCredentials.get(DeviceCredentials.class), DeviceCredentials.class)); + try { + device.setTenantId(getCurrentUser().getTenantId()); + checkEntity(device.getId(), device, Resource.DEVICE); + Device savedDevice = deviceService.saveDeviceWithCredentials(device, credentials); + checkNotNull(savedDevice); + + tbClusterService.onDeviceChange(savedDevice, null); + tbClusterService.pushMsgToCore(new DeviceNameOrTypeUpdateMsg(savedDevice.getTenantId(), + savedDevice.getId(), savedDevice.getName(), savedDevice.getType()), null); + tbClusterService.onEntityStateChange(savedDevice.getTenantId(), savedDevice.getId(), + device.getId() == null ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); + + logEntityAction(savedDevice.getId(), savedDevice, + savedDevice.getCustomerId(), + device.getId() == null ? ActionType.ADDED : ActionType.UPDATED, null); + + if (device.getId() == null) { + deviceStateService.onDeviceAdded(savedDevice); + } else { + deviceStateService.onDeviceUpdated(savedDevice); + } + return savedDevice; + } catch (Exception e) { + logEntityAction(emptyId(EntityType.DEVICE), device, + null, device.getId() == null ? ActionType.ADDED : ActionType.UPDATED, e); + throw handleException(e); + } + } } diff --git a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MModelsRepository.java b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MModelsRepository.java index e314cd8f51..e909dd8741 100644 --- a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MModelsRepository.java +++ b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MModelsRepository.java @@ -23,8 +23,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.data.domain.PageImpl; import org.springframework.stereotype.Service; -import org.thingsboard.server.common.data.lwm2m.*; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.lwm2m.LwM2mInstance; +import org.thingsboard.server.common.data.lwm2m.LwM2mObject; +import org.thingsboard.server.common.data.lwm2m.LwM2mResource; +import org.thingsboard.server.common.data.lwm2m.ServerSecurityConfig; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.transport.lwm2m.LwM2MTransportConfigBootstrap; @@ -33,17 +36,24 @@ import org.thingsboard.server.dao.service.Validator; import org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode; import java.math.BigInteger; -import java.security.*; +import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.KeyStoreException; +import java.security.PublicKey; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; -import java.security.spec.ECPublicKeySpec; import java.security.spec.ECPoint; +import java.security.spec.ECPublicKeySpec; import java.security.spec.KeySpec; -import java.util.List; import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; +import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -70,22 +80,32 @@ public class LwM2MModelsRepository { * Filter by Predicate (uses objectIds, if objectIds is null then it uses textSearch, * if textSearch is null then it uses AllList from List) */ - public List getLwm2mObjects(int[] objectIds, String textSearch) { - return getLwm2mObjects((objectIds != null && objectIds.length > 0) ? - (ObjectModel element) -> IntStream.of(objectIds).anyMatch(x -> x == element.id) : - (textSearch != null && !textSearch.isEmpty()) ? (ObjectModel element) -> element.name.contains(textSearch) : null); + public List getLwm2mObjects(int[] objectIds, String textSearch, String sortProperty, String sortOrder) { + if (objectIds == null && textSearch != null && !textSearch.isEmpty()) { + objectIds = getObjectIdFromTextSearch(textSearch); + } + int[] finalObjectIds = objectIds; + return getLwm2mObjects((objectIds != null && objectIds.length > 0 && textSearch != null && !textSearch.isEmpty()) ? + (ObjectModel element) -> IntStream.of(finalObjectIds).anyMatch(x -> x == element.id) || element.name.toLowerCase().contains(textSearch.toLowerCase()) : + (objectIds != null && objectIds.length > 0) ? + (ObjectModel element) -> IntStream.of(finalObjectIds).anyMatch(x -> x == element.id) : + (textSearch != null && !textSearch.isEmpty()) ? + (ObjectModel element) -> element.name.contains(textSearch) : + null, + sortProperty, sortOrder); } /** * @param predicate * @return list of LwM2mObject */ - private List getLwm2mObjects(Predicate predicate) { + private List getLwm2mObjects(Predicate predicate, String sortProperty, String sortOrder) { List lwM2mObjects = new ArrayList<>(); List listObjects = (predicate == null) ? this.contextServer.getModelsValue() : contextServer.getModelsValue().stream() .filter(predicate) .collect(Collectors.toList()); + listObjects.forEach(obj -> { LwM2mObject lwM2mObject = new LwM2mObject(); lwM2mObject.setId(obj.id); @@ -105,6 +125,29 @@ public class LwM2MModelsRepository { lwM2mObject.setInstances(new LwM2mInstance[]{instance}); lwM2mObjects.add(lwM2mObject); }); + return lwM2mObjects.size() > 1 ? this.sortList (lwM2mObjects, sortProperty, sortOrder) : lwM2mObjects; + } + + private List sortList (List lwM2mObjects, String sortProperty, String sortOrder) { + switch (sortProperty) { + case "name": + switch (sortOrder) { + case "ASC": + lwM2mObjects.sort((o1, o2) -> o1.getName().compareTo(o2.getName())); + break; + case "DESC": + lwM2mObjects.stream().sorted(Comparator.comparing(LwM2mObject::getName).reversed()); + break; + } + case "id": + switch (sortOrder) { + case "ASC": + lwM2mObjects.sort((o1, o2) -> Long.compare(o1.getId(), o2.getId())); + break; + case "DESC": + lwM2mObjects.sort((o1, o2) -> Long.compare(o2.getId(), o1.getId())); + } + } return lwM2mObjects; } @@ -126,13 +169,32 @@ public class LwM2MModelsRepository { * PageNumber = 1, PageSize = List.size() */ public PageData findLwm2mListObjects(PageLink pageLink) { - PageImpl page = new PageImpl(getLwm2mObjects(null, pageLink.getTextSearch())); + PageImpl page = new PageImpl(getLwm2mObjects(getObjectIdFromTextSearch(pageLink.getTextSearch()), + pageLink.getTextSearch(), + pageLink.getSortOrder().getProperty(), + pageLink.getSortOrder().getDirection().name())); PageData pageData = new PageData(page.getContent(), page.getTotalPages(), page.getTotalElements(), page.hasNext()); return pageData; } /** - * + * Filter for id Object + * @param textSearch - + * @return - return Object id only first chartAt in textSearch + */ + private int[] getObjectIdFromTextSearch(String textSearch) { + String filtered = null; + if (textSearch !=null && !textSearch.isEmpty()) { + AtomicInteger a = new AtomicInteger(); + filtered = textSearch.chars () + .mapToObj(chr -> (char) chr) + .filter(i -> Character.isDigit(i) && textSearch.charAt(a.getAndIncrement()) == i) + .collect(Collector.of(StringBuilder::new, StringBuilder::append, StringBuilder::append, StringBuilder::toString)); + } + return (filtered != null && !filtered.isEmpty()) ? new int[]{Integer.parseInt(filtered)} : new int[0]; + } + + /** * @param securityMode * @param bootstrapServerIs * @return ServerSecurityConfig more value is default: Important - port, host, publicKey @@ -143,60 +205,60 @@ public class LwM2MModelsRepository { } /** - * * @param bootstrapServerIs * @param mode * @return ServerSecurityConfig more value is default: Important - port, host, publicKey */ private ServerSecurityConfig getBootstrapServer(boolean bootstrapServerIs, LwM2MSecurityMode mode) { ServerSecurityConfig bsServ = new ServerSecurityConfig(); + bsServ.setBootstrapServerIs(bootstrapServerIs); if (bootstrapServerIs) { + bsServ.setServerId(contextBootStrap.getBootstrapServerId()); switch (mode) { case NO_SEC: bsServ.setHost(contextBootStrap.getBootstrapHost()); - bsServ.setPort(contextBootStrap.getBootstrapPort()); + bsServ.setPort(contextBootStrap.getBootstrapPortNoSecPsk()); bsServ.setServerPublicKey(""); break; case PSK: bsServ.setHost(contextBootStrap.getBootstrapSecureHost()); - bsServ.setPort(contextBootStrap.getBootstrapSecurePort()); + bsServ.setPort(contextBootStrap.getBootstrapSecurePortPsk()); bsServ.setServerPublicKey(""); break; case RPK: bsServ.setHost(contextBootStrap.getBootstrapSecureHost()); - bsServ.setPort(contextBootStrap.getBootstrapSecurePort()); + bsServ.setPort(contextBootStrap.getBootstrapSecurePortRpk()); bsServ.setServerPublicKey(getRPKPublicKey(this.contextBootStrap.getBootstrapPublicX(), this.contextBootStrap.getBootstrapPublicY())); break; case X509: bsServ.setHost(contextBootStrap.getBootstrapSecureHost()); - bsServ.setPort(contextBootStrap.getBootstrapSecurePortCert()); + bsServ.setPort(contextBootStrap.getBootstrapSecurePortX509()); bsServ.setServerPublicKey(getServerPublicKeyX509(contextBootStrap.getBootstrapAlias())); break; default: break; } } else { - bsServ.setBootstrapServerIs(bootstrapServerIs); - bsServ.setServerId(123); + bsServ.setServerId(contextServer.getServerId()); switch (mode) { case NO_SEC: bsServ.setHost(contextServer.getServerHost()); - bsServ.setPort(contextServer.getServerPort()); + bsServ.setPort(contextServer.getServerPortNoSecPsk()); bsServ.setServerPublicKey(""); break; case PSK: bsServ.setHost(contextServer.getServerSecureHost()); - bsServ.setPort(contextServer.getServerSecurePort()); + bsServ.setPort(contextServer.getServerPortPsk()); bsServ.setServerPublicKey(""); break; case RPK: bsServ.setHost(contextServer.getServerSecureHost()); - bsServ.setPort(contextServer.getServerSecurePort()); + bsServ.setPort(contextServer.getServerPortRpk()); bsServ.setServerPublicKey(getRPKPublicKey(this.contextServer.getServerPublicX(), this.contextServer.getServerPublicY())); break; case X509: bsServ.setHost(contextServer.getServerSecureHost()); - bsServ.setPort(contextServer.getServerSecurePortCert()); + bsServ.setPort(contextServer.getServerPortX509()); bsServ.setServerPublicKey(getServerPublicKeyX509(contextServer.getServerAlias())); break; default: @@ -207,25 +269,23 @@ public class LwM2MModelsRepository { } /** - * * @param alias * @return PublicKey format HexString or null */ - private String getServerPublicKeyX509 (String alias) { + private String getServerPublicKeyX509(String alias) { try { - X509Certificate serverCertificate = (X509Certificate) contextServer.getKeyStoreValue().getCertificate(alias); - return Hex.encodeHexString(serverCertificate.getEncoded()); + X509Certificate serverCertificate = (X509Certificate) contextServer.getKeyStoreValue().getCertificate(alias); + return Hex.encodeHexString(serverCertificate.getEncoded()); } catch (CertificateEncodingException | KeyStoreException e) { e.printStackTrace(); } - return null; + return null; } /** - * * @param publicServerX * @param publicServerY - * @return PublicKey format HexString or null + * @return PublicKey format HexString or null */ private String getRPKPublicKey(String publicServerX, String publicServerY) { try { @@ -241,9 +301,9 @@ public class LwM2MModelsRepository { KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), parameterSpec); /** Get keys */ - PublicKey publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec); - if (publicKey != null && publicKey.getEncoded().length > 0 ) { - return Hex.encodeHexString(publicKey.getEncoded()); + PublicKey publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec); + if (publicKey != null && publicKey.getEncoded().length > 0) { + return Hex.encodeHexString(publicKey.getEncoded()); } } } catch (GeneralSecurityException | IllegalArgumentException e) { diff --git a/application/src/main/java/org/thingsboard/server/service/transport/DefaultTransportApiService.java b/application/src/main/java/org/thingsboard/server/service/transport/DefaultTransportApiService.java index 0bdeaf360e..76f77c3889 100644 --- a/application/src/main/java/org/thingsboard/server/service/transport/DefaultTransportApiService.java +++ b/application/src/main/java/org/thingsboard/server/service/transport/DefaultTransportApiService.java @@ -49,34 +49,31 @@ import org.thingsboard.server.common.transport.util.DataDecodingEncodingService; import org.thingsboard.server.dao.device.DeviceCredentialsService; import org.thingsboard.server.dao.device.DeviceProvisionService; import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.device.provision.ProvisionFailedException; import org.thingsboard.server.dao.device.provision.ProvisionRequest; import org.thingsboard.server.dao.device.provision.ProvisionResponse; import org.thingsboard.server.dao.relation.RelationService; +import org.thingsboard.server.dao.tenant.TbTenantProfileCache; import org.thingsboard.server.dao.util.mapping.JacksonUtil; import org.thingsboard.server.gen.transport.TransportProtos; -import org.thingsboard.server.gen.transport.TransportProtos.DeviceCredentialsProto; import org.thingsboard.server.gen.transport.TransportProtos.DeviceInfoProto; -import org.thingsboard.server.gen.transport.TransportProtos.GetOrCreateDeviceFromGatewayRequestMsg; -import org.thingsboard.server.gen.transport.TransportProtos.GetOrCreateDeviceFromGatewayResponseMsg; import org.thingsboard.server.gen.transport.TransportProtos.GetEntityProfileRequestMsg; import org.thingsboard.server.gen.transport.TransportProtos.GetEntityProfileResponseMsg; +import org.thingsboard.server.gen.transport.TransportProtos.GetOrCreateDeviceFromGatewayRequestMsg; +import org.thingsboard.server.gen.transport.TransportProtos.GetOrCreateDeviceFromGatewayResponseMsg; import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceRequestMsg; -import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceResponseMsg; -import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceResponseMsgOrBuilder; import org.thingsboard.server.gen.transport.TransportProtos.ProvisionResponseStatus; import org.thingsboard.server.gen.transport.TransportProtos.TransportApiRequestMsg; import org.thingsboard.server.gen.transport.TransportProtos.TransportApiResponseMsg; import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceCredentialsResponseMsg; +import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceLwM2MCredentialsRequestMsg; import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceTokenRequestMsg; import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceX509CertRequestMsg; -import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceLwM2MCredentialsRequestMsg; import org.thingsboard.server.queue.common.TbProtoQueueMsg; import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.dao.device.provision.ProvisionFailedException; import org.thingsboard.server.service.apiusage.TbApiUsageStateService; import org.thingsboard.server.service.executors.DbCallbackExecutorService; import org.thingsboard.server.service.profile.TbDeviceProfileCache; -import org.thingsboard.server.dao.tenant.TbTenantProfileCache; import org.thingsboard.server.service.queue.TbClusterService; import org.thingsboard.server.service.state.DeviceStateService; @@ -326,6 +323,7 @@ public class DefaultTransportApiService implements TransportApiService { break; case MQTT_BASIC: case X509_CERTIFICATE: + case LWM2M_CREDENTIALS: provisionResponse.setCredentialsValue(deviceCredentials.getCredentialsValue()); break; } diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 065a0a4cb0..51c1f4f353 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -575,7 +575,13 @@ transport: timeout: "${LWM2M_TIMEOUT:120000}" # model_path_file: "${LWM2M_MODEL_PATH_FILE:./common/transport/lwm2m/src/main/resources/models/}" model_path_file: "${LWM2M_MODEL_PATH_FILE:}" - support_deprecated_ciphers_enable: "${LWM2M_SUPPORT_DEPRECATED_CIPHERS_ENABLED:true}" + recommended_ciphers: "${LWM2M_RECOMMENDED_CIPHERS:false}" + recommended_supported_groups: "${LWM2M_RECOMMENDED_SUPPORTED_GROUPS:false}" + request_pool_size: "${LWM2M_REQUEST_POOL_SIZE:100}" + request_error_pool_size: "${LWM2M_REQUEST_ERROR_POOL_SIZE:10}" + registered_pool_size: "${LWM2M_REGISTERED_POOL_SIZE:10}" + update_registered_pool_size: "${LWM2M_UPDATE_REGISTERED_POOL_SIZE:10}" + un_registered_pool_size: "${LWM2M_UN_REGISTERED_POOL_SIZE:10}" secure: # Only Certificate_x509: # To get helps about files format and how to generate it, see: https://github.com/eclipse/leshan/wiki/Credential-files-format @@ -588,24 +594,19 @@ transport: root_alias: "${LWM2M_SERVER_ROOT_CA:rootca}" enable_gen_psk_rpk: "${ENABLE_GEN_PSK_RPK:true}" server: + id: "${LWM2M_SERVER_ID:123}" bind_address: "${LWM2M_BIND_ADDRESS:0.0.0.0}" - bind_port: "${LWM2M_BIND_PORT:5685}" - bind_port_cert: "${LWM2M_BIND_PORT_CERT:5687}" + bind_port_no_sec_psk: "${LWM2M_BIND_PORT_NO_SEC_PSK:5685}" + bind_port_no_sec_rpk: "${LWM2M_BIND_PORT_NO_SEC_RPK:5687}" + bind_port_no_sec_x509: "${LWM2M_BIND_PORT_NO_SEC_X509:5689}" secure: - start_all: "${START_SERVER_ALL:true}" - #leshan.core (V1_1) - #DTLS security modes: - #0: Pre-Shared Key mode - #1: Raw Public Key mode - #2: Certificate mode X509 - #3: NoSec mode * - #OMA-TS-LightweightM2M_Core-V1_1_1-20190617-A (add) - #4: Certificate mode X509 with EST - # If only startAll == false - dtls_mode: "${LWM2M_SECURITY_MODE:1}" bind_address: "${LWM2M_BIND_ADDRESS:0.0.0.0}" - bind_port: "${LWM2M_BIND_PORT_SEC:5686}" - bind_port_cert: "${LWM2M_BIND_PORT_SEC_CERT:5688}" + start_psk: "${START_SERVER_PSK:true}" + start_rpk: "${START_SERVER_RPK:true}" + start_x509: "${START_SERVER_X509:true}" + bind_port_psk: "${LWM2M_BIND_PORT_SEC_PSK:5686}" + bind_port_rpk: "${LWM2M_BIND_PORT_SEC_RPK:5688}" + bind_port_x509: "${LWM2M_BIND_PORT_SEC_X509:5690}" # Only RPK: Public & Private Key # create_rpk: "${CREATE_RPK:}" public_x: "${LWM2M_SERVER_PUBLIC_X:405354ea8893471d9296afbc8b020a5c6201b0bb25812a53b849d4480fa5f069}" @@ -615,23 +616,26 @@ transport: alias: "${LWM2M_KEYSTORE_ALIAS_SERVER:server}" bootstrap: enable: "${BOOTSTRAP:true}" + id: "${LWM2M_SERVER_ID:111}" bind_address: "${LWM2M_BIND_ADDRESS_BS:0.0.0.0}" - bind_port: "${LWM2M_BIND_PORT_BS:5689}" - bind_port_cert: "${LWM2M_BIND_PORT_SER_BS:5691}" + bind_port_no_sec_psk: "${LWM2M_BIND_PORT_NO_SEC_BS:5691}" + bind_port_no_sec_rpk: "${LWM2M_BIND_PORT_NO_SEC_BS:5693}" + bind_port_no_sec_x509: "${LWM2M_BIND_PORT_NO_SEC_BS:5695}" secure: - start_all: "${START_BOOTSTRAP_ALL:true}" - # If only startAll == false - dtls_mode: "${LWM2M_SECURITY_MODE_BS:1}" bind_address: "${LWM2M_BIND_ADDRESS_BS:0.0.0.0}" - bind_port: "${LWM2M_BIND_PORT_SEC_BS:5690}" - bind_port_cert: "${LWM2M_BIND_PORT_SEC_CERT_BS:5692}" + start_psk: "${START_SERVER_PSK_BS:true}" + start_rpk: "${START_SERVER_RPK_BS:true}" + start_x509: "${START_SERVER_X509_BS:true}" + bind_port_psk: "${LWM2M_BIND_PORT_SEC_PSK_BS:5692}" + bind_port_rpk: "${LWM2M_BIND_PORT_SER_RPK_BS:5694}" + bind_port_x509: "${LWM2M_BIND_PORT_SEC_X509_BS:5696}" # Only RPK: Public & Private Key public_x: "${LWM2M_SERVER_PUBLIC_X_BS:993ef2b698c6a9c0c1d8be78b13a9383c0854c7c7c7a504d289b403794648183}" public_y: "${LWM2M_SERVER_PUBLIC_Y_BS:267412d5fc4e5ceb2257cb7fd7f76ebdac2fa9aa100afb162e990074cc0bfaa2}" private_s: "${LWM2M_SERVER_PRIVATE_S_BS:9dbdbb073fc63570693a9aaf1013414e261c571f27e27fc6a8c1c2ad9347875a}" # Only Certificate_x509: alias: "${LWM2M_KEYSTORE_ALIAS_BOOTSTRAP:bootstrap}" - # Redis + # Redis redis_url: "${LWM2M_REDIS_URL:''}" swagger: diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceService.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceService.java index 715313538d..a54bb7af7e 100644 --- a/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceService.java +++ b/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceService.java @@ -27,6 +27,7 @@ import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.dao.device.provision.ProvisionRequest; import java.util.List; @@ -45,6 +46,8 @@ public interface DeviceService { Device saveDeviceWithAccessToken(Device device, String accessToken); + Device saveDeviceWithCredentials(Device device, DeviceCredentials deviceCredentials); + Device assignDeviceToCustomer(TenantId tenantId, DeviceId deviceId, CustomerId customerId); Device unassignDeviceFromCustomer(TenantId tenantId, DeviceId deviceId); diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/Device.java b/common/data/src/main/java/org/thingsboard/server/common/data/Device.java index ca8e5f5575..64c608ecb8 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/Device.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/Device.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.core.JsonProcessingException; import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; import org.thingsboard.server.common.data.device.data.DeviceData; -import org.thingsboard.server.common.data.device.profile.DeviceProfileData; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; @@ -64,6 +63,17 @@ public class Device extends SearchTextBasedWithAdditionalInfo implemen this.setDeviceData(device.getDeviceData()); } + public Device updateDevice(Device device) { + this.tenantId = device.getTenantId(); + this.customerId = device.getCustomerId(); + this.name = device.getName(); + this.type = device.getType(); + this.label = device.getLabel(); + this.deviceProfileId = device.getDeviceProfileId(); + this.setDeviceData(device.getDeviceData()); + return this; + } + public TenantId getTenantId() { return tenantId; } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/security/DeviceCredentialsType.java b/common/data/src/main/java/org/thingsboard/server/common/data/security/DeviceCredentialsType.java index 84a634a100..6b214ecb38 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/security/DeviceCredentialsType.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/security/DeviceCredentialsType.java @@ -21,6 +21,4 @@ public enum DeviceCredentialsType { X509_CERTIFICATE, MQTT_BASIC, LWM2M_CREDENTIALS - - } diff --git a/common/queue/src/main/proto/queue.proto b/common/queue/src/main/proto/queue.proto index 08a0d0ba97..1c2a128eb6 100644 --- a/common/queue/src/main/proto/queue.proto +++ b/common/queue/src/main/proto/queue.proto @@ -77,6 +77,7 @@ enum CredentialsType { ACCESS_TOKEN = 0; X509_CERTIFICATE = 1; MQTT_BASIC = 2; + LWM2M_CREDENTIALS = 3; } message KeyValueProto { diff --git a/common/transport/lwm2m/pom.xml b/common/transport/lwm2m/pom.xml index a904d1e12f..44a764be2b 100644 --- a/common/transport/lwm2m/pom.xml +++ b/common/transport/lwm2m/pom.xml @@ -65,15 +65,10 @@ ch.qos.logback logback-classic - org.eclipse.leshan leshan-server-cf - - - - org.eclipse.leshan leshan-client-cf @@ -83,12 +78,6 @@ org.eclipse.leshan leshan-server-redis - - - - - - org.springframework.boot spring-boot-starter-test @@ -107,14 +96,20 @@ org.eclipse.californium californium-core - ${californium.version} - test-jar + test-jar test + + org.eclipse.californium + californium-core + + + + + org.eclipse.californium element-connector - ${californium.version} test-jar test diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/LwM2MTransportBootstrapServerConfiguration.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/LwM2MTransportBootstrapServerConfiguration.java index a1f056ff30..13584cadb5 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/LwM2MTransportBootstrapServerConfiguration.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/LwM2MTransportBootstrapServerConfiguration.java @@ -18,6 +18,7 @@ package org.thingsboard.server.transport.lwm2m.bootstrap; import lombok.extern.slf4j.Slf4j; import org.eclipse.californium.scandium.config.DtlsConnectorConfig; import org.eclipse.leshan.core.model.StaticModel; +import org.eclipse.leshan.core.util.Hex; import org.eclipse.leshan.server.bootstrap.BootstrapSessionManager; import org.eclipse.leshan.server.californium.bootstrap.LeshanBootstrapServer; import org.eclipse.leshan.server.californium.bootstrap.LeshanBootstrapServerBuilder; @@ -28,18 +29,42 @@ import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import org.thingsboard.server.transport.lwm2m.bootstrap.secure.LwM2MBootstrapSecurityStore; import org.thingsboard.server.transport.lwm2m.bootstrap.secure.LwM2MInMemoryBootstrapConfigStore; -import org.thingsboard.server.transport.lwm2m.bootstrap.secure.LwM2MSetSecurityStoreBootstrap; import org.thingsboard.server.transport.lwm2m.bootstrap.secure.LwM2mDefaultBootstrapSessionManager; import org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode; import org.thingsboard.server.transport.lwm2m.server.LwM2MTransportContextServer; -import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.X509; + +import java.math.BigInteger; +import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.security.interfaces.ECPublicKey; +import java.security.spec.ECGenParameterSpec; +import java.security.spec.ECParameterSpec; +import java.security.spec.ECPoint; +import java.security.spec.ECPrivateKeySpec; +import java.security.spec.ECPublicKeySpec; +import java.security.spec.KeySpec; +import java.util.Arrays; + +import static org.eclipse.californium.scandium.dtls.cipher.CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256; +import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.NO_SEC; +import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.PSK; import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.RPK; +import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.X509; import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.getCoapConfig; @Slf4j @Component -@ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true'&& '${transport.lwm2m.bootstrap.enable:false}'=='true') || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true'&& '${transport.lwm2m.bootstrap.enable}'=='true')") +@ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true'&& '${transport.lwm2m.bootstrap.enable:false}'=='true') || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled:false}'=='true'&& '${transport.lwm2m.bootstrap.enable:false}'=='true')") public class LwM2MTransportBootstrapServerConfiguration { + private PublicKey publicKey; + private PrivateKey privateKey; @Autowired private LwM2MTransportContextBootstrap contextBs; @@ -53,27 +78,35 @@ public class LwM2MTransportBootstrapServerConfiguration { @Autowired private LwM2MInMemoryBootstrapConfigStore lwM2MInMemoryBootstrapConfigStore; - @Primary - @Bean(name = "leshanBootstrapCert") - public LeshanBootstrapServer getLeshanBootstrapServerCert() { - log.info("Prepare and start BootstrapServerCert... PostConstruct"); - return getLeshanBootstrapServer(this.contextBs.getCtxBootStrap().getBootstrapPortCert(), this.contextBs.getCtxBootStrap().getBootstrapSecurePortCert(), X509); + @Bean(name = "leshanBootstrapX509") + @ConditionalOnExpression("('${transport.lwm2m.bootstrap.secure.start_x509:false}'=='true')") + public LeshanBootstrapServer getLeshanBootstrapServerX509() { + log.info("Prepare and start BootstrapServerX509... PostConstruct"); + return getLeshanBootstrapServer(this.contextBs.getCtxBootStrap().getBootstrapPortNoSecX509(), this.contextBs.getCtxBootStrap().getBootstrapSecurePortX509(), X509); + } + + @Bean(name = "leshanBootstrapPsk") + @ConditionalOnExpression("('${transport.lwm2m.bootstrap.secure.start_psk:false}'=='true')") + public LeshanBootstrapServer getLeshanBootstrapServerPsk() { + log.info("Prepare and start BootstrapServerRsk... PostConstruct"); + return getLeshanBootstrapServer(this.contextBs.getCtxBootStrap().getBootstrapPortNoSecPsk(), this.contextBs.getCtxBootStrap().getBootstrapSecurePortPsk(), PSK); } - @Bean(name = "leshanBootstrapRPK") - public LeshanBootstrapServer getLeshanBootstrapServerRPK() { - log.info("Prepare and start BootstrapServerRPK... PostConstruct"); - return getLeshanBootstrapServer(this.contextBs.getCtxBootStrap().getBootstrapPort(), this.contextBs.getCtxBootStrap().getBootstrapSecurePort(), RPK); + @Bean(name = "leshanBootstrapRpk") + @ConditionalOnExpression("('${transport.lwm2m.bootstrap.secure.start_rpk:false}'=='true')") + public LeshanBootstrapServer getLeshanBootstrapServerRpk() { + log.info("Prepare and start BootstrapServerRpk... PostConstruct"); + return getLeshanBootstrapServer(this.contextBs.getCtxBootStrap().getBootstrapPortNoSecRpk(), this.contextBs.getCtxBootStrap().getBootstrapSecurePortRpk(), RPK); } - public LeshanBootstrapServer getLeshanBootstrapServer(Integer bootstrapPort, Integer bootstrapSecurePort, LwM2MSecurityMode dtlsMode) { + public LeshanBootstrapServer getLeshanBootstrapServer(Integer bootstrapPortNoSec, Integer bootstrapSecurePort, LwM2MSecurityMode dtlsMode) { LeshanBootstrapServerBuilder builder = new LeshanBootstrapServerBuilder(); - builder.setLocalAddress(this.contextBs.getCtxBootStrap().getBootstrapHost(), bootstrapPort); + builder.setLocalAddress(this.contextBs.getCtxBootStrap().getBootstrapHost(), bootstrapPortNoSec); builder.setLocalSecureAddress(this.contextBs.getCtxBootStrap().getBootstrapSecureHost(), bootstrapSecurePort); /** Create CoAP Config */ - builder.setCoapConfig(getCoapConfig ()); + builder.setCoapConfig(getCoapConfig (bootstrapPortNoSec, bootstrapSecurePort)); /** ConfigStore */ builder.setConfigStore(lwM2MInMemoryBootstrapConfigStore); @@ -84,13 +117,22 @@ public class LwM2MTransportBootstrapServerConfiguration { /** Define model provider (Create Models )*/ builder.setModel(new StaticModel(contextS.getCtxServer().getModelsValue())); + /** Create credentials */ + LwM2MSetSecurityStoreBootstrap(builder, dtlsMode); + /** Create and Set DTLS Config */ DtlsConnectorConfig.Builder dtlsConfig = new DtlsConnectorConfig.Builder(); - dtlsConfig.setRecommendedCipherSuitesOnly(contextS.getCtxServer().isSupportDeprecatedCiphersEnable()); + if (dtlsMode==PSK) { + dtlsConfig.setRecommendedCipherSuitesOnly(this.contextS.getCtxServer().isRecommendedCiphers()); + dtlsConfig.setRecommendedSupportedGroupsOnly(this.contextS.getCtxServer().isRecommendedSupportedGroups()); + dtlsConfig.setSupportedCipherSuites(TLS_PSK_WITH_AES_128_CBC_SHA256); + } + else { + dtlsConfig.setRecommendedCipherSuitesOnly(this.contextS.getCtxServer().isRecommendedCiphers()); +// dtlsConfig.setRecommendedSupportedGroupsOnly(false); + } builder.setDtlsConfig(dtlsConfig); - /** Create credentials */ - new LwM2MSetSecurityStoreBootstrap(builder, contextBs, contextS, dtlsMode); BootstrapSessionManager sessionManager = new LwM2mDefaultBootstrapSessionManager(lwM2MBootstrapSecurityStore); builder.setSessionManager(sessionManager); @@ -98,4 +140,151 @@ public class LwM2MTransportBootstrapServerConfiguration { /** Create BootstrapServer */ return builder.build(); } + + public void LwM2MSetSecurityStoreBootstrap(LeshanBootstrapServerBuilder builder, LwM2MSecurityMode dtlsMode) { + + /** Set securityStore with new registrationStore */ + + switch (dtlsMode) { + /** Use No_Sec only */ + case NO_SEC: + setServerWithX509Cert(builder, NO_SEC.code); + break; + /** Use PSK/RPK */ + case PSK: + break; + case RPK: + setRPK(builder); + break; + case X509: + setServerWithX509Cert(builder, X509.code); + break; + /** Use X509_EST only */ + case X509_EST: + // TODO support sentinel pool and make pool configurable + break; + /** Use ather X509, PSK, No_Sec ?? */ + default: + break; + } + } + + private void setRPK(LeshanBootstrapServerBuilder builder) { + try { + /** Get Elliptic Curve Parameter spec for secp256r1 */ + AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC"); + algoParameters.init(new ECGenParameterSpec("secp256r1")); + ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class); + if (this.contextBs.getCtxBootStrap().getBootstrapPublicX() != null && !this.contextBs.getCtxBootStrap().getBootstrapPublicX().isEmpty() && this.contextBs.getCtxBootStrap().getBootstrapPublicY() != null && !this.contextBs.getCtxBootStrap().getBootstrapPublicY().isEmpty()) { + /** Get point values */ + byte[] publicX = Hex.decodeHex(this.contextBs.getCtxBootStrap().getBootstrapPublicX().toCharArray()); + byte[] publicY = Hex.decodeHex(this.contextBs.getCtxBootStrap().getBootstrapPublicY().toCharArray()); + /** Create key specs */ + KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), + parameterSpec); + /** Get keys */ + this.publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec); + } + if (this.contextBs.getCtxBootStrap().getBootstrapPrivateS() != null && !this.contextBs.getCtxBootStrap().getBootstrapPrivateS().isEmpty()) { + /** Get point values */ + byte[] privateS = Hex.decodeHex(this.contextBs.getCtxBootStrap().getBootstrapPrivateS().toCharArray()); + /** Create key specs */ + KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec); + /** Get keys */ + this.privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec); + } + if (this.publicKey != null && this.publicKey.getEncoded().length > 0 && + this.privateKey != null && this.privateKey.getEncoded().length > 0) { + builder.setPublicKey(this.publicKey); + builder.setPrivateKey(this.privateKey); + this.contextBs.getCtxBootStrap().setBootstrapPublicKey(this.publicKey); + getParamsRPK(); + } + } catch (GeneralSecurityException | IllegalArgumentException e) { + log.error("[{}] Failed generate Server PSK/RPK", e.getMessage()); + throw new RuntimeException(e); + } + } + + private void setServerWithX509Cert(LeshanBootstrapServerBuilder builder, int securityModeCode) { + try { + if (this.contextS.getCtxServer().getKeyStoreValue() != null) { + KeyStore keyStoreServer = this.contextS.getCtxServer().getKeyStoreValue(); + setBuilderX509(builder); + X509Certificate rootCAX509Cert = (X509Certificate) keyStoreServer.getCertificate(this.contextS.getCtxServer().getRootAlias()); + if (rootCAX509Cert != null && securityModeCode == X509.code) { + X509Certificate[] trustedCertificates = new X509Certificate[1]; + trustedCertificates[0] = rootCAX509Cert; + builder.setTrustedCertificates(trustedCertificates); + } else { + /** by default trust all */ + builder.setTrustedCertificates(new X509Certificate[0]); + } + } + else { + /** by default trust all */ + builder.setTrustedCertificates(new X509Certificate[0]); + log.error("Unable to load X509 files for BootStrapServer"); + } + } catch (KeyStoreException ex) { + log.error("[{}] Unable to load X509 files server", ex.getMessage()); + } + + } + + private void setBuilderX509(LeshanBootstrapServerBuilder builder) { + /** + * For deb => KeyStorePathFile == yml or commandline: KEY_STORE_PATH_FILE + * For idea => KeyStorePathResource == common/transport/lwm2m/src/main/resources/credentials: in LwM2MTransportContextServer: credentials/serverKeyStore.jks + */ + try { + X509Certificate serverCertificate = (X509Certificate) this.contextS.getCtxServer().getKeyStoreValue().getCertificate(this.contextBs.getCtxBootStrap().getBootstrapAlias()); + this.privateKey = (PrivateKey) this.contextS.getCtxServer().getKeyStoreValue().getKey(this.contextBs.getCtxBootStrap().getBootstrapAlias(), this.contextS.getCtxServer().getKeyStorePasswordServer() == null ? null : this.contextS.getCtxServer().getKeyStorePasswordServer().toCharArray()); + if (this.privateKey != null && this.privateKey.getEncoded().length > 0) { + builder.setPrivateKey(this.privateKey); + } + if (serverCertificate != null) { + builder.setCertificateChain(new X509Certificate[]{serverCertificate}); + this.infoParamsX509(serverCertificate); + } + } catch (Exception ex) { + log.error("[{}] Unable to load KeyStore files server", ex.getMessage()); + } + } + + private void getParamsRPK() { + if (this.publicKey instanceof ECPublicKey) { + /** Get x coordinate */ + byte[] x = ((ECPublicKey) this.publicKey).getW().getAffineX().toByteArray(); + if (x[0] == 0) + x = Arrays.copyOfRange(x, 1, x.length); + + /** Get Y coordinate */ + byte[] y = ((ECPublicKey) this.publicKey).getW().getAffineY().toByteArray(); + if (y[0] == 0) + y = Arrays.copyOfRange(y, 1, y.length); + + /** Get Curves params */ + String params = ((ECPublicKey) this.publicKey).getParams().toString(); + log.info( + " \nBootstrap uses RPK : \n Elliptic Curve parameters : [{}] \n Public x coord : [{}] \n Public y coord : [{}] \n Public Key (Hex): [{}] \n Private Key (Hex): [{}]", + params, Hex.encodeHexString(x), Hex.encodeHexString(y), + Hex.encodeHexString(this.publicKey.getEncoded()), + Hex.encodeHexString(this.privateKey.getEncoded())); + } else { + throw new IllegalStateException("Unsupported Public Key Format (only ECPublicKey supported)."); + } + } + + private void infoParamsX509(X509Certificate certificate) { + try { + log.info("BootStrap uses X509 : \n X509 Certificate (Hex): [{}] \n Private Key (Hex): [{}]", + Hex.encodeHexString(certificate.getEncoded()), + Hex.encodeHexString(this.privateKey.getEncoded())); + } catch (CertificateEncodingException e) { + log.error("", e); + } + } + + } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/LwM2MTransportBootstrapServerInitializer.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/LwM2MTransportBootstrapServerInitializer.java index cb927a76b9..68bc6ee51c 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/LwM2MTransportBootstrapServerInitializer.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/LwM2MTransportBootstrapServerInitializer.java @@ -14,57 +14,56 @@ * limitations under the License. */ package org.thingsboard.server.transport.lwm2m.bootstrap; + import lombok.extern.slf4j.Slf4j; import org.eclipse.leshan.server.californium.bootstrap.LeshanBootstrapServer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.stereotype.Service; -import org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Slf4j @Service -@ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled}'=='true'&& '${transport.lwm2m.bootstrap.enable}'=='true') || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true'&& '${transport.lwm2m.bootstrap.enable}'=='true')") +@ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true'&& '${transport.lwm2m.bootstrap.enable:false}'=='true') || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled:false}'=='true'&& '${transport.lwm2m.bootstrap.enable:false}'=='true')") public class LwM2MTransportBootstrapServerInitializer { - @Autowired - @Qualifier("leshanBootstrapCert") + @Autowired(required = false) + @Qualifier("leshanBootstrapX509") private LeshanBootstrapServer lhBServerCert; - @Autowired - @Qualifier("leshanBootstrapRPK") - private LeshanBootstrapServer lhBServerRPK; + @Autowired(required = false) + @Qualifier("leshanBootstrapPsk") + private LeshanBootstrapServer lhBServerPsk; + + @Autowired(required = false) + @Qualifier("leshanBootstrapRpk") + private LeshanBootstrapServer lhBServerRpk; @Autowired private LwM2MTransportContextBootstrap contextBS; @PostConstruct public void init() { - if (this.contextBS.getCtxBootStrap().isBootstrapStartAll()) { - this.lhBServerCert.start(); - this.lhBServerRPK.start(); + if (this.contextBS.getCtxBootStrap().getBootstrapStartPsk()) { + this.lhBServerPsk.start(); + } + if (this.contextBS.getCtxBootStrap().getBootstrapStartRpk()) { + this.lhBServerRpk.start(); } - else { - if (this.contextBS.getCtxBootStrap().getBootStrapDtlsMode() == LwM2MSecurityMode.X509.code) { - this.lhBServerCert.start(); - } - else { - this.lhBServerRPK.start(); - } + if (this.contextBS.getCtxBootStrap().getBootstrapStartX509()) { + this.lhBServerCert.start(); } } @PreDestroy public void shutdown() throws InterruptedException { log.info("Stopping LwM2M transport Bootstrap Server!"); - try { - lhBServerCert.destroy(); - lhBServerRPK.destroy(); - } finally { - } + lhBServerPsk.destroy(); + lhBServerRpk.destroy(); + lhBServerCert.destroy(); log.info("LwM2M transport Bootstrap Server stopped!"); } } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapSecurityStore.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapSecurityStore.java index 0b06f02547..75e6f78d35 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapSecurityStore.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapSecurityStore.java @@ -29,28 +29,41 @@ import org.eclipse.leshan.server.security.BootstrapSecurityStore; import org.eclipse.leshan.server.security.SecurityInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.stereotype.Component; -import org.thingsboard.server.transport.lwm2m.secure.LwM2MGetSecurityInfo; +import org.springframework.stereotype.Service; +import org.thingsboard.server.gen.transport.TransportProtos; import org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode; +import org.thingsboard.server.transport.lwm2m.secure.LwM2mCredentialsSecurityInfoValidator; import org.thingsboard.server.transport.lwm2m.secure.ReadResultSecurityStore; +import org.thingsboard.server.transport.lwm2m.server.LwM2MSessionMsgListener; +import org.thingsboard.server.transport.lwm2m.server.LwM2MTransportContextServer; +import org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler; import org.thingsboard.server.transport.lwm2m.utils.TypeServer; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.List; +import java.util.UUID; -import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.*; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.BOOTSTRAP_SERVER; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LOG_LW2M_ERROR; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LOG_LW2M_INFO; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LWM2M_SERVER; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.SERVERS; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.getBootstrapParametersFromThingsboard; @Slf4j -@Component("LwM2MBootstrapSecurityStore") +@Service("LwM2MBootstrapSecurityStore") @ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' && '${transport.lwm2m.bootstrap.enable:false}'=='true') || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true' && '${transport.lwm2m.bootstrap.enable}'=='true')") public class LwM2MBootstrapSecurityStore implements BootstrapSecurityStore { private final EditableBootstrapConfigStore bootstrapConfigStore; @Autowired - LwM2MGetSecurityInfo lwM2MGetSecurityInfo; + LwM2mCredentialsSecurityInfoValidator lwM2MCredentialsSecurityInfoValidator; + + @Autowired + public LwM2MTransportContextServer context; public LwM2MBootstrapSecurityStore(EditableBootstrapConfigStore bootstrapConfigStore) { this.bootstrapConfigStore = bootstrapConfigStore; @@ -59,8 +72,8 @@ public class LwM2MBootstrapSecurityStore implements BootstrapSecurityStore { @Override public List getAllByEndpoint(String endPoint) { String endPointKey = endPoint; - ReadResultSecurityStore store = lwM2MGetSecurityInfo.getSecurityInfo(endPointKey, TypeServer.BOOTSTRAP); - if (store.getBootstrapJsonCredential() != null) { + ReadResultSecurityStore store = lwM2MCredentialsSecurityInfoValidator.createAndValidateCredentialsSecurityInfo(endPointKey, TypeServer.BOOTSTRAP); + if (store.getBootstrapJsonCredential() != null && store.getSecurityMode() < LwM2MSecurityMode.DEFAULT_MODE.code) { /** add value to store from BootstrapJson */ this.setBootstrapConfigScurityInfo(store); BootstrapConfig bsConfigNew = store.getBootstrapConfig(); @@ -73,7 +86,7 @@ public class LwM2MBootstrapSecurityStore implements BootstrapSecurityStore { } bootstrapConfigStore.add(endPoint, bsConfigNew); } catch (InvalidConfigurationException e) { - e.printStackTrace(); + log.error("", e); } return store.getSecurityInfo() == null ? null : Arrays.asList(store.getSecurityInfo()); } @@ -83,17 +96,16 @@ public class LwM2MBootstrapSecurityStore implements BootstrapSecurityStore { @Override public SecurityInfo getByIdentity(String identity) { - ReadResultSecurityStore store = lwM2MGetSecurityInfo.getSecurityInfo(identity, TypeServer.BOOTSTRAP); - /** add value to store from BootstrapJson */ - this.setBootstrapConfigScurityInfo(store); - - if (store.getSecurityMode() < LwM2MSecurityMode.DEFAULT_MODE.code) { + ReadResultSecurityStore store = lwM2MCredentialsSecurityInfoValidator.createAndValidateCredentialsSecurityInfo(identity, TypeServer.BOOTSTRAP); + if (store.getBootstrapJsonCredential() != null && store.getSecurityMode() < LwM2MSecurityMode.DEFAULT_MODE.code) { + /** add value to store from BootstrapJson */ + this.setBootstrapConfigScurityInfo(store); BootstrapConfig bsConfig = store.getBootstrapConfig(); if (bsConfig.security != null) { try { bootstrapConfigStore.add(store.getEndPoint(), bsConfig); } catch (InvalidConfigurationException e) { - e.printStackTrace(); + log.error("", e); } return store.getSecurityInfo(); } @@ -141,28 +153,36 @@ public class LwM2MBootstrapSecurityStore implements BootstrapSecurityStore { private LwM2MBootstrapConfig getParametersBootstrap(ReadResultSecurityStore store) { try { JsonObject bootstrapJsonCredential = store.getBootstrapJsonCredential(); - ObjectMapper mapper = new ObjectMapper(); - LwM2MBootstrapConfig lwM2MBootstrapConfig = mapper.readValue(bootstrapJsonCredential.toString(), LwM2MBootstrapConfig.class); - JsonObject bootstrapObject = getBootstrapParametersFromThingsboard(store.getDeviceProfile()); - lwM2MBootstrapConfig.servers = mapper.readValue(bootstrapObject.get(SERVERS).toString(), LwM2MBootstrapServers.class); - LwM2MServerBootstrap profileServerBootstrap = mapper.readValue(bootstrapObject.get(BOOTSTRAP_SERVER).toString(), LwM2MServerBootstrap.class); - LwM2MServerBootstrap profileLwm2mServer = mapper.readValue(bootstrapObject.get(LWM2M_SERVER).toString(), LwM2MServerBootstrap.class); - if (getValidatedSecurityMode(lwM2MBootstrapConfig.bootstrapServer, profileServerBootstrap, lwM2MBootstrapConfig.lwm2mServer, profileLwm2mServer)) { - lwM2MBootstrapConfig.bootstrapServer = new LwM2MServerBootstrap(lwM2MBootstrapConfig.bootstrapServer, profileServerBootstrap); - lwM2MBootstrapConfig.lwm2mServer = new LwM2MServerBootstrap(lwM2MBootstrapConfig.lwm2mServer, profileLwm2mServer); - return lwM2MBootstrapConfig; - } - else { - log.error(" [{}] Different values SecurityMode between of client and profile.", store.getEndPoint()); - log.error(LOG_LW2M_ERROR + " getParametersBootstrap: [{}] Different values SecurityMode between of client and profile.", store.getEndPoint()); - String logMsg = String.format(LOG_LW2M_ERROR + " getParametersBootstrap: %s Different values SecurityMode between of client and profile.", store.getEndPoint()); -// sentLogsToThingsboard(logMsg, store.getEndPoint()); - return null; + if (bootstrapJsonCredential != null) { + ObjectMapper mapper = new ObjectMapper(); + LwM2MBootstrapConfig lwM2MBootstrapConfig = mapper.readValue(bootstrapJsonCredential.toString(), LwM2MBootstrapConfig.class); + JsonObject bootstrapObject = getBootstrapParametersFromThingsboard(store.getDeviceProfile()); + lwM2MBootstrapConfig.servers = mapper.readValue(bootstrapObject.get(SERVERS).toString(), LwM2MBootstrapServers.class); + LwM2MServerBootstrap profileServerBootstrap = mapper.readValue(bootstrapObject.get(BOOTSTRAP_SERVER).toString(), LwM2MServerBootstrap.class); + LwM2MServerBootstrap profileLwm2mServer = mapper.readValue(bootstrapObject.get(LWM2M_SERVER).toString(), LwM2MServerBootstrap.class); + UUID sessionUUiD = UUID.randomUUID(); + TransportProtos.SessionInfoProto sessionInfo = context.getValidateSessionInfo(store.getMsg(), sessionUUiD.getMostSignificantBits(), sessionUUiD.getLeastSignificantBits()); + context.getTransportService().registerAsyncSession(sessionInfo, new LwM2MSessionMsgListener(null, sessionInfo)); + if (this.getValidatedSecurityMode(lwM2MBootstrapConfig.bootstrapServer, profileServerBootstrap, lwM2MBootstrapConfig.lwm2mServer, profileLwm2mServer)) { + lwM2MBootstrapConfig.bootstrapServer = new LwM2MServerBootstrap(lwM2MBootstrapConfig.bootstrapServer, profileServerBootstrap); + lwM2MBootstrapConfig.lwm2mServer = new LwM2MServerBootstrap(lwM2MBootstrapConfig.lwm2mServer, profileLwm2mServer); + String logMsg = String.format(LOG_LW2M_INFO + ": getParametersBootstrap: %s Access connect client with bootstrap server.", store.getEndPoint()); + context.sentParametersOnThingsboard(context.getTelemetryMsgObject(logMsg), LwM2MTransportHandler.DEVICE_TELEMETRY_TOPIC, sessionInfo); + return lwM2MBootstrapConfig; + } else { + log.error(" [{}] Different values SecurityMode between of client and profile.", store.getEndPoint()); + log.error(LOG_LW2M_ERROR + " getParametersBootstrap: [{}] Different values SecurityMode between of client and profile.", store.getEndPoint()); + String logMsg = String.format(LOG_LW2M_ERROR + ": getParametersBootstrap: %s Different values SecurityMode between of client and profile.", store.getEndPoint()); + context.sentParametersOnThingsboard(context.getTelemetryMsgObject(logMsg), LwM2MTransportHandler.DEVICE_TELEMETRY_TOPIC, sessionInfo); + return null; + } } } catch (JsonProcessingException e) { log.error("Unable to decode Json or Certificate for [{}] [{}]", store.getEndPoint(), e.getMessage()); return null; } + log.error("Unable to decode Json or Certificate for [{}]", store.getEndPoint()); + return null; } /** @@ -175,7 +195,7 @@ public class LwM2MBootstrapSecurityStore implements BootstrapSecurityStore { * @return false if not sync between SecurityMode of Bootstrap credential and profile */ private boolean getValidatedSecurityMode(LwM2MServerBootstrap bootstrapFromCredential, LwM2MServerBootstrap profileServerBootstrap, LwM2MServerBootstrap lwm2mFromCredential, LwM2MServerBootstrap profileLwm2mServer) { - return (bootstrapFromCredential.getSecurityMode().equals(profileServerBootstrap.getSecurityMode()) && + return (bootstrapFromCredential.getSecurityMode().equals(profileServerBootstrap.getSecurityMode()) && lwm2mFromCredential.getSecurityMode().equals(profileLwm2mServer.getSecurityMode())); } } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MSetSecurityStoreBootstrap.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MSetSecurityStoreBootstrap.java deleted file mode 100644 index f648799204..0000000000 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MSetSecurityStoreBootstrap.java +++ /dev/null @@ -1,205 +0,0 @@ -/** - * Copyright © 2016-2020 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.lwm2m.bootstrap.secure; - -import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import org.eclipse.leshan.core.util.Hex; -import org.eclipse.leshan.server.californium.bootstrap.LeshanBootstrapServerBuilder; -import org.eclipse.leshan.server.security.EditableSecurityStore; -import org.thingsboard.server.transport.lwm2m.bootstrap.LwM2MTransportContextBootstrap; -import org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode; -import org.thingsboard.server.transport.lwm2m.server.LwM2MTransportContextServer; - -import java.math.BigInteger; -import java.security.AlgorithmParameters; -import java.security.KeyStore; -import java.security.PublicKey; -import java.security.PrivateKey; -import java.security.KeyFactory; -import java.security.GeneralSecurityException; -import java.security.KeyStoreException; -import java.security.cert.X509Certificate; -import java.security.interfaces.ECPublicKey; -import java.security.spec.ECGenParameterSpec; -import java.security.spec.ECParameterSpec; -import java.security.spec.ECPublicKeySpec; -import java.security.spec.ECPoint; -import java.security.spec.KeySpec; -import java.security.spec.ECPrivateKeySpec; -import java.util.Arrays; - -import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.NO_SEC; -import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.X509; - -@Slf4j -@Data -public class LwM2MSetSecurityStoreBootstrap { - - private KeyStore keyStore; - private PublicKey publicKey; - private PrivateKey privateKey; - private LwM2MTransportContextBootstrap contextBs; - private LwM2MTransportContextServer contextS; - private LeshanBootstrapServerBuilder builder; - EditableSecurityStore securityStore; - - public LwM2MSetSecurityStoreBootstrap(LeshanBootstrapServerBuilder builder, LwM2MTransportContextBootstrap contextBs, LwM2MTransportContextServer contextS, LwM2MSecurityMode dtlsMode) { - this.builder = builder; - this.contextBs = contextBs; - this.contextS = contextS; - /** Set securityStore with new registrationStore */ - - switch (dtlsMode) { - /** Use No_Sec only */ - case NO_SEC: - setServerWithX509Cert(NO_SEC.code); - break; - /** Use PSK/RPK */ - case PSK: - case RPK: - setRPK(); - break; - case X509: - setServerWithX509Cert(X509.code); - break; - /** Use X509_EST only */ - case X509_EST: - // TODO support sentinel pool and make pool configurable - break; - /** Use ather X509, PSK, No_Sec ?? */ - default: - break; - } - } - - private void setRPK() { - try { - /** Get Elliptic Curve Parameter spec for secp256r1 */ - AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC"); - algoParameters.init(new ECGenParameterSpec("secp256r1")); - ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class); - if (this.contextBs.getCtxBootStrap().getBootstrapPublicX() != null && !this.contextBs.getCtxBootStrap().getBootstrapPublicX().isEmpty() && this.contextBs.getCtxBootStrap().getBootstrapPublicY() != null && !this.contextBs.getCtxBootStrap().getBootstrapPublicY().isEmpty()) { - /** Get point values */ - byte[] publicX = Hex.decodeHex(this.contextBs.getCtxBootStrap().getBootstrapPublicX().toCharArray()); - byte[] publicY = Hex.decodeHex(this.contextBs.getCtxBootStrap().getBootstrapPublicY().toCharArray()); - /** Create key specs */ - KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), - parameterSpec); - /** Get keys */ - this.publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec); - } - if (this.contextBs.getCtxBootStrap().getBootstrapPrivateS() != null && !this.contextBs.getCtxBootStrap().getBootstrapPrivateS().isEmpty()) { - /** Get point values */ - byte[] privateS = Hex.decodeHex(this.contextBs.getCtxBootStrap().getBootstrapPrivateS().toCharArray()); - /** Create key specs */ - KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec); - /** Get keys */ - this.privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec); - } - if (this.publicKey != null && this.publicKey.getEncoded().length > 0 && - this.privateKey != null && this.privateKey.getEncoded().length > 0) { - this.builder.setPublicKey(this.publicKey); - this.builder.setPrivateKey(this.privateKey); - this.contextBs.getCtxBootStrap().setBootstrapPublicKey(this.publicKey); - getParamsRPK(); - } - } catch (GeneralSecurityException | IllegalArgumentException e) { - log.error("[{}] Failed generate Server PSK/RPK", e.getMessage()); - throw new RuntimeException(e); - } - } - - private void setServerWithX509Cert(int securityModeCode) { - try { - if (this.contextS.getCtxServer().getKeyStoreValue() != null) { - KeyStore keyStoreServer = this.contextS.getCtxServer().getKeyStoreValue(); - setBuilderX509(); - X509Certificate rootCAX509Cert = (X509Certificate) keyStoreServer.getCertificate(this.contextS.getCtxServer().getRootAlias()); - if (rootCAX509Cert != null && securityModeCode == X509.code) { - X509Certificate[] trustedCertificates = new X509Certificate[1]; - trustedCertificates[0] = rootCAX509Cert; - this.builder.setTrustedCertificates(trustedCertificates); - } else { - /** by default trust all */ - this.builder.setTrustedCertificates(new X509Certificate[0]); - } - } - else { - /** by default trust all */ - this.builder.setTrustedCertificates(new X509Certificate[0]); - log.error("Unable to load X509 files for BootStrapServer"); - } - } catch (KeyStoreException ex) { - log.error("[{}] Unable to load X509 files server", ex.getMessage()); - } - - } - - private void setBuilderX509() { - /** - * For deb => KeyStorePathFile == yml or commandline: KEY_STORE_PATH_FILE - * For idea => KeyStorePathResource == common/transport/lwm2m/src/main/resources/credentials: in LwM2MTransportContextServer: credentials/serverKeyStore.jks - */ - try { - X509Certificate serverCertificate = (X509Certificate) this.contextS.getCtxServer().getKeyStoreValue().getCertificate(this.contextBs.getCtxBootStrap().getBootstrapAlias()); - this.privateKey = (PrivateKey) this.contextS.getCtxServer().getKeyStoreValue().getKey(this.contextBs.getCtxBootStrap().getBootstrapAlias(), this.contextS.getCtxServer().getKeyStorePasswordServer() == null ? null : this.contextS.getCtxServer().getKeyStorePasswordServer().toCharArray()); - if (this.privateKey != null && this.privateKey.getEncoded().length > 0) { - this.builder.setPrivateKey(this.privateKey); - } - if (serverCertificate != null) { - this.builder.setCertificateChain(new X509Certificate[]{serverCertificate}); - this.contextBs.getCtxBootStrap().setBootstrapCertificate(serverCertificate); - } - } catch (Exception ex) { - log.error("[{}] Unable to load KeyStore files server", ex.getMessage()); - } - } - - private void getParamsRPK() { - if (this.publicKey instanceof ECPublicKey) { - /** Get x coordinate */ - byte[] x = ((ECPublicKey) this.publicKey).getW().getAffineX().toByteArray(); - if (x[0] == 0) - x = Arrays.copyOfRange(x, 1, x.length); - - /** Get Y coordinate */ - byte[] y = ((ECPublicKey) this.publicKey).getW().getAffineY().toByteArray(); - if (y[0] == 0) - y = Arrays.copyOfRange(y, 1, y.length); - - /** Get Curves params */ - String params = ((ECPublicKey) this.publicKey).getParams().toString(); - log.info( - " \nBootstrap uses RPK : \n Elliptic Curve parameters : [{}] \n Public x coord : [{}] \n Public y coord : [{}] \n Public Key (Hex): [{}] \n Private Key (Hex): [{}]", - params, Hex.encodeHexString(x), Hex.encodeHexString(y), - Hex.encodeHexString(this.publicKey.getEncoded()), - Hex.encodeHexString(this.privateKey.getEncoded())); - } else { - throw new IllegalStateException("Unsupported Public Key Format (only ECPublicKey supported)."); - } - } - -// private void getParamsX509() { -// try { -// log.info("BootStrap uses X509 : \n X509 Certificate (Hex): [{}] \n Private Key (Hex): [{}]", -// Hex.encodeHexString(this.certificate.getEncoded()), -// Hex.encodeHexString(this.privateKey.getEncoded())); -// } catch (CertificateEncodingException e) { -// e.printStackTrace(); -// } -// } -} diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2mDefaultBootstrapSessionManager.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2mDefaultBootstrapSessionManager.java index db8a520266..6608635ee0 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2mDefaultBootstrapSessionManager.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2mDefaultBootstrapSessionManager.java @@ -49,7 +49,6 @@ public class LwM2mDefaultBootstrapSessionManager extends DefaultBootstrapSession this.securityChecker = securityChecker; } - @Override public BootstrapSession begin(String endpoint, Identity clientIdentity) { boolean authorized; if (bsSecurityStore != null) { diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LWM2MGenerationPSkRPkECC.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LWM2MGenerationPSkRPkECC.java index 1d70ae2d83..0921df1104 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LWM2MGenerationPSkRPkECC.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LWM2MGenerationPSkRPkECC.java @@ -73,15 +73,15 @@ public class LWM2MGenerationPSkRPkECC { try { kpg = KeyPairGenerator.getInstance(algorithm, provider); } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); + log.error("", e); } catch (NoSuchProviderException e) { - e.printStackTrace(); + log.error("", e); } ECGenParameterSpec ecsp = new ECGenParameterSpec(nameParameterSpec); try { kpg.initialize(ecsp); } catch (InvalidAlgorithmParameterException e) { - e.printStackTrace(); + log.error("", e); } KeyPair kp = kpg.genKeyPair(); diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LwM2MGetSecurityInfo.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LwM2mCredentialsSecurityInfoValidator.java similarity index 77% rename from common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LwM2MGetSecurityInfo.java rename to common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LwM2mCredentialsSecurityInfoValidator.java index ad63e21633..80b4772378 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LwM2MGetSecurityInfo.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LwM2mCredentialsSecurityInfoValidator.java @@ -39,12 +39,15 @@ import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.*; +import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.NO_SEC; +import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.PSK; +import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.RPK; +import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.X509; @Slf4j @Component("LwM2MGetSecurityInfo") @ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' ) || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") -public class LwM2MGetSecurityInfo { +public class LwM2mCredentialsSecurityInfoValidator { @Autowired public LwM2MTransportContextServer contextS; @@ -53,7 +56,13 @@ public class LwM2MGetSecurityInfo { public LwM2MTransportContextBootstrap contextBS; - public ReadResultSecurityStore getSecurityInfo(String endPoint, TypeServer keyValue) { + /** + * Request to thingsboard Response from thingsboard ValidateDeviceLwM2MCredentials + * @param endPoint - + * @param keyValue - + * @return ValidateDeviceCredentialsResponseMsg and SecurityInfo + */ + public ReadResultSecurityStore createAndValidateCredentialsSecurityInfo(String endPoint, TypeServer keyValue) { CountDownLatch latch = new CountDownLatch(1); final ReadResultSecurityStore[] resultSecurityStore = new ReadResultSecurityStore[1]; contextS.getTransportService().process(ValidateDeviceLwM2MCredentialsRequestMsg.newBuilder().setCredentialsId(endPoint).build(), @@ -61,7 +70,7 @@ public class LwM2MGetSecurityInfo { @Override public void onSuccess(ValidateDeviceCredentialsResponseMsg msg) { String credentialsBody = msg.getCredentialsBody(); - resultSecurityStore[0] = putSecurityInfo(endPoint, msg.getDeviceInfo().getDeviceName(), credentialsBody, keyValue); + resultSecurityStore[0] = createSecurityInfo(endPoint, credentialsBody, keyValue); resultSecurityStore[0].setMsg(msg); Optional deviceProfileOpt = LwM2MTransportHandler.decode(msg.getProfileBody().toByteArray()); deviceProfileOpt.ifPresent(profile -> resultSecurityStore[0].setDeviceProfile(profile)); @@ -70,20 +79,27 @@ public class LwM2MGetSecurityInfo { @Override public void onError(Throwable e) { - log.trace("[{}] Failed to process credentials PSK: {}", endPoint, e); - resultSecurityStore[0] = putSecurityInfo(endPoint, null, null, null); + log.trace("[{}] [{}] Failed to process credentials ", endPoint, e); + resultSecurityStore[0] = createSecurityInfo(endPoint, null, null); latch.countDown(); } }); try { latch.await(contextS.getCtxServer().getTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { - e.printStackTrace(); + log.error("Failed to await credentials!", e); } return resultSecurityStore[0]; } - private ReadResultSecurityStore putSecurityInfo(String endPoint, String deviceName, String jsonStr, TypeServer keyValue) { + /** + * Create new SecurityInfo + * @param endPoint - + * @param jsonStr - + * @param keyValue - + * @return SecurityInfo + */ + private ReadResultSecurityStore createSecurityInfo(String endPoint, String jsonStr, TypeServer keyValue) { ReadResultSecurityStore result = new ReadResultSecurityStore(); JsonObject objectMsg = LwM2MTransportHandler.validateJson(jsonStr); if (objectMsg != null && !objectMsg.isJsonNull()) { @@ -99,20 +115,21 @@ public class LwM2MGetSecurityInfo { if (keyValue.equals(TypeServer.BOOTSTRAP)) { result.setBootstrapJsonCredential(object); result.setEndPoint(endPoint); + result.setSecurityMode(LwM2MSecurityMode.fromSecurityMode(object.get("bootstrapServer").getAsJsonObject().get("securityMode").getAsString().toLowerCase()).code); } else { LwM2MSecurityMode lwM2MSecurityMode = LwM2MSecurityMode.fromSecurityMode(object.get("securityConfigClientMode").getAsString().toLowerCase()); switch (lwM2MSecurityMode) { case NO_SEC: - getClientSecurityInfoNoSec(result); + createClientSecurityInfoNoSec(result); break; case PSK: - getClientSecurityInfoPSK(result, endPoint, object); + createClientSecurityInfoPSK(result, endPoint, object); break; case RPK: - getClientSecurityInfoRPK(result, endPoint, object); + createClientSecurityInfoRPK(result, endPoint, object); break; case X509: - getClientSecurityInfoX509(result, endPoint); + createClientSecurityInfoX509(result, endPoint); break; default: break; @@ -123,12 +140,12 @@ public class LwM2MGetSecurityInfo { return result; } - private void getClientSecurityInfoNoSec(ReadResultSecurityStore result) { + private void createClientSecurityInfoNoSec(ReadResultSecurityStore result) { result.setSecurityInfo(null); result.setSecurityMode(NO_SEC.code); } - private void getClientSecurityInfoPSK(ReadResultSecurityStore result, String endPoint, JsonObject object) { + private void createClientSecurityInfoPSK(ReadResultSecurityStore result, String endPoint, JsonObject object) { /** PSK Deserialization */ String identity = (object.has("identity") && object.get("identity").isJsonPrimitive()) ? object.get("identity").getAsString() : null; if (identity != null && !identity.isEmpty()) { @@ -148,7 +165,7 @@ public class LwM2MGetSecurityInfo { } } - private void getClientSecurityInfoRPK(ReadResultSecurityStore result, String endpoint, JsonObject object) { + private void createClientSecurityInfoRPK(ReadResultSecurityStore result, String endpoint, JsonObject object) { try { if (object.has("key") && object.get("key").isJsonPrimitive()) { byte[] rpkkey = Hex.decodeHex(object.get("key").getAsString().toLowerCase().toCharArray()); @@ -163,7 +180,7 @@ public class LwM2MGetSecurityInfo { } } - private void getClientSecurityInfoX509(ReadResultSecurityStore result, String endpoint) { + private void createClientSecurityInfoX509(ReadResultSecurityStore result, String endpoint) { result.setSecurityInfo(SecurityInfo.newX509CertInfo(endpoint)); result.setSecurityMode(X509.code); } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MSessionMsgListener.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MSessionMsgListener.java index bf88427879..7c3450486e 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MSessionMsgListener.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MSessionMsgListener.java @@ -33,17 +33,17 @@ import java.util.Optional; @Slf4j public class LwM2MSessionMsgListener implements GenericFutureListener>, SessionMsgListener { - private LwM2MTransportService service; + private LwM2MTransportServiceImpl service; private TransportProtos.SessionInfoProto sessionInfo; - LwM2MSessionMsgListener(LwM2MTransportService service, TransportProtos.SessionInfoProto sessionInfo) { + public LwM2MSessionMsgListener(LwM2MTransportServiceImpl service, TransportProtos.SessionInfoProto sessionInfo) { this.service = service; this.sessionInfo = sessionInfo; } @Override public void onGetAttributesResponse(GetAttributeResponseMsg getAttributesResponse) { - log.info("[{}] attributesResponse", getAttributesResponse); + this.service.onGetAttributesResponse(getAttributesResponse, this.sessionInfo); } @Override diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportContextServer.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportContextServer.java index 4bddd9a481..7199c3c31c 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportContextServer.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportContextServer.java @@ -30,15 +30,26 @@ package org.thingsboard.server.transport.lwm2m.server; * limitations under the License. */ +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.stereotype.Component; import org.thingsboard.server.common.transport.TransportContext; +import org.thingsboard.server.common.transport.TransportService; +import org.thingsboard.server.common.transport.TransportServiceCallback; +import org.thingsboard.server.common.transport.adaptor.AdaptorException; import org.thingsboard.server.common.transport.lwm2m.LwM2MTransportConfigServer; +import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.transport.lwm2m.server.adaptors.LwM2MJsonAdaptor; +import org.thingsboard.server.transport.lwm2m.server.secure.LwM2mInMemorySecurityStore; import javax.annotation.PostConstruct; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LOG_LW2M_TELEMETRY; + @Slf4j @Component @ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true') || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") @@ -47,14 +58,87 @@ public class LwM2MTransportContextServer extends TransportContext { private LwM2MTransportConfigServer ctxServer; @Autowired - LwM2MTransportConfigServer lwM2MTransportConfigServer; + protected LwM2MTransportConfigServer lwM2MTransportConfigServer; + + @Autowired + private TransportService transportService; + + @Getter + @Autowired + private LwM2MJsonAdaptor adaptor; + + @Autowired + LwM2mInMemorySecurityStore lwM2mInMemorySecurityStore; @PostConstruct public void init() { this.ctxServer = lwM2MTransportConfigServer; } - public LwM2MTransportConfigServer getCtxServer () { + public LwM2MTransportConfigServer getCtxServer() { return this.ctxServer; } + + /** + * Sent to Thingsboard Attribute || Telemetry + * + * @param msg - JsonObject: [{name: value}] + * @return - dummy + */ + private TransportServiceCallback getPubAckCallbackSentAttrTelemetry(final T msg) { + return new TransportServiceCallback() { + @Override + public void onSuccess(Void dummy) { + log.trace("Success to publish msg: {}, dummy: {}", msg, dummy); + } + + @Override + public void onError(Throwable e) { + log.trace("[{}] Failed to publish msg: {}", msg, e); + } + }; + } + + public void sentParametersOnThingsboard(JsonElement msg, String topicName, TransportProtos.SessionInfoProto sessionInfo) { + try { + if (topicName.equals(LwM2MTransportHandler.DEVICE_ATTRIBUTES_TOPIC)) { + TransportProtos.PostAttributeMsg postAttributeMsg = adaptor.convertToPostAttributes(msg); + TransportServiceCallback call = this.getPubAckCallbackSentAttrTelemetry(postAttributeMsg); + transportService.process(sessionInfo, postAttributeMsg, this.getPubAckCallbackSentAttrTelemetry(call)); + } else if (topicName.equals(LwM2MTransportHandler.DEVICE_TELEMETRY_TOPIC)) { + TransportProtos.PostTelemetryMsg postTelemetryMsg = adaptor.convertToPostTelemetry(msg); + TransportServiceCallback call = this.getPubAckCallbackSentAttrTelemetry(postTelemetryMsg); + transportService.process(sessionInfo, postTelemetryMsg, this.getPubAckCallbackSentAttrTelemetry(call)); + } + } catch (AdaptorException e) { + log.error("[{}] Failed to process publish msg [{}]", topicName, e); + log.info("[{}] Closing current session due to invalid publish", topicName); + } + } + + public JsonObject getTelemetryMsgObject(String logMsg) { + JsonObject telemetries = new JsonObject(); + telemetries.addProperty(LOG_LW2M_TELEMETRY, logMsg); + return telemetries; + } + + /** + * @return - sessionInfo after access connect client + */ + public TransportProtos.SessionInfoProto getValidateSessionInfo(TransportProtos.ValidateDeviceCredentialsResponseMsg msg, long mostSignificantBits, long leastSignificantBits) { + return TransportProtos.SessionInfoProto.newBuilder() + .setNodeId(this.getNodeId()) + .setSessionIdMSB(mostSignificantBits) + .setSessionIdLSB(leastSignificantBits) + .setDeviceIdMSB(msg.getDeviceInfo().getDeviceIdMSB()) + .setDeviceIdLSB(msg.getDeviceInfo().getDeviceIdLSB()) + .setTenantIdMSB(msg.getDeviceInfo().getTenantIdMSB()) + .setTenantIdLSB(msg.getDeviceInfo().getTenantIdLSB()) + .setDeviceName(msg.getDeviceInfo().getDeviceName()) + .setDeviceType(msg.getDeviceInfo().getDeviceType()) + .setDeviceProfileIdLSB(msg.getDeviceInfo().getDeviceProfileIdLSB()) + .setDeviceProfileIdMSB(msg.getDeviceInfo().getDeviceProfileIdMSB()) + .build(); + } + } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportHandler.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportHandler.java index d922f2b1c5..dbca7a8f5b 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportHandler.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportHandler.java @@ -16,7 +16,6 @@ package org.thingsboard.server.transport.lwm2m.server; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; @@ -24,57 +23,60 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.eclipse.californium.core.network.config.NetworkConfig; import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.node.LwM2mMultipleResource; import org.eclipse.leshan.core.node.LwM2mNode; import org.eclipse.leshan.core.node.LwM2mObject; import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; import org.eclipse.leshan.core.node.LwM2mSingleResource; -import org.eclipse.leshan.core.node.LwM2mMultipleResource; +import org.eclipse.leshan.core.node.codec.CodecException; import org.eclipse.leshan.core.util.Hex; -import org.eclipse.leshan.server.californium.LeshanServer; import org.eclipse.leshan.server.californium.LeshanServerBuilder; import org.nustaq.serialization.FSTConfiguration; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.device.profile.Lwm2mDeviceProfileTransportConfiguration; +import org.thingsboard.server.common.transport.TransportServiceCallback; import org.thingsboard.server.transport.lwm2m.server.client.AttrTelemetryObserveValue; +import org.thingsboard.server.transport.lwm2m.server.client.LwM2MClient; -import javax.annotation.PostConstruct; import java.io.File; import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Optional; -import java.util.Map; import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; +import java.util.Date; import java.util.LinkedList; -import java.util.Collections; +import java.util.Optional; @Slf4j -@Component("LwM2MTransportHandler") -@ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' )|| ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") -public class LwM2MTransportHandler{ +//@Component("LwM2MTransportHandler") +//@ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' )|| ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") +public class LwM2MTransportHandler { // We choose a default timeout a bit higher to the MAX_TRANSMIT_WAIT(62-93s) which is the time from starting to // send a Confirmable message to the time when an acknowledgement is no longer expected. - public static final long DEFAULT_TIMEOUT = 2 * 60 * 1000l; // 2min in ms - public static final String OBSERVE_ATTRIBUTE_TELEMETRY = "observeAttr"; - public static final String KEYNAME = "keyName"; + + public static final String BASE_DEVICE_API_TOPIC = "v1/devices/me"; public static final String ATTRIBUTE = "attribute"; public static final String TELEMETRY = "telemetry"; + private static final String REQUEST = "/request"; + private static final String RESPONSE = "/response"; + private static final String ATTRIBUTES = "/" + ATTRIBUTE; + public static final String TELEMETRIES = "/" + TELEMETRY; + public static final String ATTRIBUTES_RESPONSE = ATTRIBUTES + RESPONSE; + public static final String ATTRIBUTES_REQUEST = ATTRIBUTES + REQUEST; + public static final String DEVICE_ATTRIBUTES_RESPONSE = ATTRIBUTES_RESPONSE + "/"; + public static final String DEVICE_ATTRIBUTES_REQUEST = ATTRIBUTES_REQUEST + "/"; + public static final String DEVICE_ATTRIBUTES_TOPIC = BASE_DEVICE_API_TOPIC + ATTRIBUTES; + public static final String DEVICE_TELEMETRY_TOPIC = BASE_DEVICE_API_TOPIC + TELEMETRIES; + + public static final long DEFAULT_TIMEOUT = 2 * 60 * 1000L; // 2min in ms + public static final String OBSERVE_ATTRIBUTE_TELEMETRY = "observeAttr"; + public static final String KEYNAME = "keyName"; public static final String OBSERVE = "observe"; public static final String BOOTSTRAP = "bootstrap"; public static final String SERVERS = "servers"; public static final String LWM2M_SERVER = "lwm2mServer"; public static final String BOOTSTRAP_SERVER = "bootstrapServer"; - public static final String BASE_DEVICE_API_TOPIC = "v1/devices/me"; - public static final String DEVICE_ATTRIBUTES_TOPIC = BASE_DEVICE_API_TOPIC + "/attributes"; - public static final String DEVICE_TELEMETRY_TOPIC = BASE_DEVICE_API_TOPIC + "/telemetry"; + public static final String LOG_LW2M_TELEMETRY = "logLwm2m"; public static final String LOG_LW2M_INFO = "info"; public static final String LOG_LW2M_ERROR = "error"; @@ -91,44 +93,55 @@ public class LwM2MTransportHandler{ /** * Replaces the Object Instance or the Resource(s) with the new value provided in the “Write” operation. (see * section 5.3.3 of the LW M2M spec). + * if all resources are to be replaced */ public static final String POST_TYPE_OPER_WRITE_REPLACE = "replace"; /** * Adds or updates Resources provided in the new value and leaves other existing Resources unchanged. (see section * 5.3.3 of the LW M2M spec). + * if this is a partial update request */ public static final String PUT_TYPE_OPER_WRITE_UPDATE = "update"; public static final String PUT_TYPE_OPER_WRITE_ATTRIBUTES = "wright-attributes"; public static final String EVENT_AWAKE = "AWAKE"; + public static final String SERVICE_CHANNEL = "SERVICE"; + public static final String RESPONSE_CHANNEL = "RESP"; - private static Gson gson = null; +// @Autowired +// @Qualifier("LeshanServerCert") +// private LeshanServer lhServerCert; +// +// @Autowired +// @Qualifier("LeshanServerNoSecPskRpk") +// private LeshanServer lhServerNoSecPskRpk; - @Autowired - @Qualifier("LeshanServerCert") - private LeshanServer lhServerCert; +// @Autowired +// @Qualifier("ServerListenerCert") +// private LwM2mServerListener serverListenerCert; +// +// @Autowired +// @Qualifier("ServerListenerNoSecPskRpk") +// private LwM2mServerListener serverListenerNoSecPskRpk; - @Autowired - @Qualifier("leshanServerNoSecPskRpk") - private LeshanServer lhServerNoSecPskRpk; - @Autowired - private LwM2MTransportService service; +// @PostConstruct +// public void init() { +// try { +// serverListenerCert.init(lhServerCert); +// this.lhServerCert.getRegistrationService().addListener(serverListenerCert.registrationListener); +// this.lhServerCert.getPresenceService().addListener(serverListenerCert.presenceListener); +// this.lhServerCert.getObservationService().addListener(serverListenerCert.observationListener); +// serverListenerNoSecPskRpk.init(lhServerNoSecPskRpk); +// this.lhServerNoSecPskRpk.getRegistrationService().addListener(serverListenerNoSecPskRpk.registrationListener); +// this.lhServerNoSecPskRpk.getPresenceService().addListener(serverListenerNoSecPskRpk.presenceListener); +// this.lhServerNoSecPskRpk.getObservationService().addListener(serverListenerNoSecPskRpk.observationListener); +// } catch (Exception e) { +// log.error("init [{}]", e.toString()); +// } +// } - - @PostConstruct - public void init() { - LwM2mServerListener lwM2mServerListener = new LwM2mServerListener(lhServerCert, service); - this.lhServerCert.getRegistrationService().addListener(lwM2mServerListener.registrationListener); - this.lhServerCert.getPresenceService().addListener(lwM2mServerListener.presenceListener); - this.lhServerCert.getObservationService().addListener(lwM2mServerListener.observationListener); - lwM2mServerListener = new LwM2mServerListener(lhServerNoSecPskRpk, service); - this.lhServerNoSecPskRpk.getRegistrationService().addListener(lwM2mServerListener.registrationListener); - this.lhServerNoSecPskRpk.getPresenceService().addListener(lwM2mServerListener.presenceListener); - this.lhServerNoSecPskRpk.getObservationService().addListener(lwM2mServerListener.observationListener); - } - - public static NetworkConfig getCoapConfig() { + public static NetworkConfig getCoapConfig(Integer serverPortNoSec, Integer serverSecurePort) { NetworkConfig coapConfig; File configFile = new File(NetworkConfig.DEFAULT_FILE_NAME); if (configFile.isFile()) { @@ -138,28 +151,26 @@ public class LwM2MTransportHandler{ coapConfig = LeshanServerBuilder.createDefaultNetworkConfig(); coapConfig.store(configFile); } + coapConfig.setString("COAP_PORT", Integer.toString(serverPortNoSec)); + coapConfig.setString("COAP_SECURE_PORT", Integer.toString(serverSecurePort)); return coapConfig; } - public static String getValueTypeToString (Object value, ResourceModel.Type type) { + public static boolean equalsResourceValue(Object valueOld, Object valueNew, ResourceModel.Type type, LwM2mPath resourcePath) throws CodecException { switch (type) { - case STRING: // String - case OBJLNK: // ObjectLink - return value.toString(); - case INTEGER: // Long - return Long.toString((long) value); - case BOOLEAN: // Boolean - return Boolean.toString((Boolean) value); - case FLOAT: // Double - return Double.toString((Float)value); - case TIME: // Date - String DATE_FORMAT = "MMM d, yyyy HH:mm a"; - DateFormat formatter = new SimpleDateFormat(DATE_FORMAT); - return formatter.format(new Date((Long) Integer.toUnsignedLong(Integer.valueOf((Integer) value)))); - case OPAQUE: // byte[] value, base64 - return Hex.encodeHexString((byte[])value); + case BOOLEAN: + case INTEGER: + case FLOAT: + return String.valueOf(valueOld).equals(String.valueOf(valueNew)); + case TIME: + return ((Date) valueOld).getTime() == ((Date) valueNew).getTime(); + case STRING: + case OBJLNK: + return valueOld.equals(valueNew); + case OPAQUE: + return Hex.decodeHex(((String) valueOld).toCharArray()).equals(Hex.decodeHex(((String) valueNew).toCharArray())); default: - return null; + throw new CodecException("Invalid value type for resource %s, type %s", resourcePath, type); } } @@ -182,26 +193,25 @@ public class LwM2MTransportHandler{ attrTelemetryObserveValue.setPostAttributeProfile(profilesConfigData.get(ATTRIBUTE).getAsJsonArray()); attrTelemetryObserveValue.setPostTelemetryProfile(profilesConfigData.get(TELEMETRY).getAsJsonArray()); attrTelemetryObserveValue.setPostObserveProfile(profilesConfigData.get(OBSERVE).getAsJsonArray()); - return attrTelemetryObserveValue; + return attrTelemetryObserveValue; } /** - * @return deviceProfileBody with Observe&Attribute&Telemetry From Thingsboard * Example: with pathResource (use only pathResource) * property: "observeAttr" * {"keyName": { - * "/3/0/1": "modelNumber", - * "/3/0/0": "manufacturer", - * "/3/0/2": "serialNumber" - * }, + * "/3/0/1": "modelNumber", + * "/3/0/0": "manufacturer", + * "/3/0/2": "serialNumber" + * }, * "attribute":["/2/0/1","/3/0/9"], * "telemetry":["/1/0/1","/2/0/1","/6/0/1"], * "observe":["/2/0","/2/0/0","/4/0/2"]} */ public static JsonObject getObserveAttrTelemetryFromThingsboard(DeviceProfile deviceProfile) { if (deviceProfile != null && ((Lwm2mDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration()).getProperties().size() > 0) { - Lwm2mDeviceProfileTransportConfiguration lwm2mDeviceProfileTransportConfiguration = (Lwm2mDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration(); +// Lwm2mDeviceProfileTransportConfiguration lwm2mDeviceProfileTransportConfiguration = (Lwm2mDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration(); Object observeAttr = ((Lwm2mDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration()).getProperties(); try { ObjectMapper mapper = new ObjectMapper(); @@ -209,7 +219,7 @@ public class LwM2MTransportHandler{ JsonObject objectMsg = (observeAttrStr != null) ? validateJson(observeAttrStr) : null; return (getValidateCredentialsBodyFromThingsboard(objectMsg)) ? objectMsg.get(OBSERVE_ATTRIBUTE_TELEMETRY).getAsJsonObject() : null; } catch (IOException e) { - e.printStackTrace(); + log.error("", e); } } return null; @@ -217,7 +227,6 @@ public class LwM2MTransportHandler{ public static JsonObject getBootstrapParametersFromThingsboard(DeviceProfile deviceProfile) { if (deviceProfile != null && ((Lwm2mDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration()).getProperties().size() > 0) { - Lwm2mDeviceProfileTransportConfiguration lwm2mDeviceProfileTransportConfiguration = (Lwm2mDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration(); Object bootstrap = ((Lwm2mDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration()).getProperties(); try { ObjectMapper mapper = new ObjectMapper(); @@ -225,7 +234,7 @@ public class LwM2MTransportHandler{ JsonObject objectMsg = (bootstrapStr != null) ? validateJson(bootstrapStr) : null; return (getValidateBootstrapProfileFromThingsboard(objectMsg)) ? objectMsg.get(BOOTSTRAP).getAsJsonObject() : null; } catch (IOException e) { - e.printStackTrace(); + log.error("", e); } } return null; @@ -276,7 +285,7 @@ public class LwM2MTransportHandler{ jsonValidFlesh = jsonValidFlesh.replaceAll("\n", ""); jsonValidFlesh = jsonValidFlesh.replaceAll("\t", ""); jsonValidFlesh = jsonValidFlesh.replaceAll(" ", ""); - String jsonValid = (jsonValidFlesh.substring(0, 1).equals("\"") && jsonValidFlesh.substring(jsonValidFlesh.length() - 1).equals("\"")) ? jsonValidFlesh.substring(1, jsonValidFlesh.length() - 1) : jsonValidFlesh; + String jsonValid = (jsonValidFlesh.charAt(0) == '"' && jsonValidFlesh.charAt(jsonValidFlesh.length() - 1) == '"') ? jsonValidFlesh.substring(1, jsonValidFlesh.length() - 1) : jsonValidFlesh; try { object = new JsonParser().parse(jsonValid).getAsJsonObject(); } catch (JsonSyntaxException e) { @@ -288,7 +297,7 @@ public class LwM2MTransportHandler{ public static Optional decode(byte[] byteArray) { try { - FSTConfiguration config = FSTConfiguration.createDefaultConfiguration();; + FSTConfiguration config = FSTConfiguration.createDefaultConfiguration(); T msg = (T) config.asObject(byteArray); return Optional.ofNullable(msg); } catch (IllegalArgumentException e) { @@ -297,37 +306,29 @@ public class LwM2MTransportHandler{ } } - /** - * Equals to Map for values - * @param map1 - * @param map2 - * @param - * @return - */ - public static > boolean mapsEquals(Map map1, Map map2) { - List values1 = new ArrayList(map1.values()); - List values2 = new ArrayList(map2.values()); - Collections.sort(values1); - Collections.sort(values2); - return values1.equals(values2); - } - - public static String convertCamelCase (String str) { - str = str.toLowerCase().replace("/[^a-z ]+/g", " "); - str = str.replace("/^(.)|\\s(.)/g", "$1"); - str = str.replace("/[^a-zA-Z]+/g", ""); - return str; - } - - public static String splitCamelCaseString(String s){ - LinkedList linkedListOut = new LinkedList(); + public static String splitCamelCaseString(String s) { + LinkedList linkedListOut = new LinkedList<>(); LinkedList linkedList = new LinkedList((Arrays.asList(s.split(" ")))); - linkedList.stream().forEach(str-> { + linkedList.forEach(str -> { String strOut = str.replaceAll("\\W", "").replaceAll("_", "").toUpperCase(); - if (strOut.length()>1) linkedListOut.add(strOut.substring(0, 1) + strOut.substring(1).toLowerCase()); + if (strOut.length() > 1) linkedListOut.add(strOut.charAt(0) + strOut.substring(1).toLowerCase()); else linkedListOut.add(strOut); }); linkedListOut.set(0, (linkedListOut.get(0).substring(0, 1).toLowerCase() + linkedListOut.get(0).substring(1))); return StringUtils.join(linkedListOut, ""); } + + public static TransportServiceCallback getAckCallback(LwM2MClient lwM2MClient, int requestId, String typeTopic) { + return new TransportServiceCallback() { + @Override + public void onSuccess(Void dummy) { + log.trace("[{}] [{}] - requestId [{}] - EndPoint , Access AckCallback", typeTopic, requestId, lwM2MClient.getEndPoint()); + } + + @Override + public void onError(Throwable e) { + log.trace("[{}] Failed to publish msg", e.toString()); + } + }; + } } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportRequest.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportRequest.java index 45a85b16bb..d5884b5b86 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportRequest.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportRequest.java @@ -20,26 +20,28 @@ import org.eclipse.californium.core.coap.Response; import org.eclipse.leshan.core.attributes.Attribute; import org.eclipse.leshan.core.attributes.AttributeSet; import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.node.LwM2mNode; +import org.eclipse.leshan.core.node.LwM2mPath; import org.eclipse.leshan.core.node.LwM2mSingleResource; import org.eclipse.leshan.core.node.ObjectLink; import org.eclipse.leshan.core.observation.Observation; +import org.eclipse.leshan.core.request.CancelObservationRequest; import org.eclipse.leshan.core.request.ContentFormat; -import org.eclipse.leshan.core.request.WriteRequest; import org.eclipse.leshan.core.request.DiscoverRequest; import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.request.ExecuteRequest; import org.eclipse.leshan.core.request.ObserveRequest; -import org.eclipse.leshan.core.request.CancelObservationRequest; import org.eclipse.leshan.core.request.ReadRequest; -import org.eclipse.leshan.core.request.ExecuteRequest; import org.eclipse.leshan.core.request.WriteAttributesRequest; -import org.eclipse.leshan.core.response.ResponseCallback; -import org.eclipse.leshan.core.response.LwM2mResponse; -import org.eclipse.leshan.core.response.ObserveResponse; -import org.eclipse.leshan.core.response.ReadResponse; +import org.eclipse.leshan.core.request.WriteRequest; import org.eclipse.leshan.core.response.CancelObservationResponse; import org.eclipse.leshan.core.response.DeleteResponse; -import org.eclipse.leshan.core.response.ExecuteResponse; import org.eclipse.leshan.core.response.DiscoverResponse; +import org.eclipse.leshan.core.response.ExecuteResponse; +import org.eclipse.leshan.core.response.LwM2mResponse; +import org.eclipse.leshan.core.response.ObserveResponse; +import org.eclipse.leshan.core.response.ReadResponse; +import org.eclipse.leshan.core.response.ResponseCallback; import org.eclipse.leshan.core.response.WriteAttributesResponse; import org.eclipse.leshan.core.response.WriteResponse; import org.eclipse.leshan.core.util.Hex; @@ -50,6 +52,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.stereotype.Service; import org.thingsboard.server.transport.lwm2m.server.client.LwM2MClient; +import org.thingsboard.server.transport.lwm2m.utils.LwM2mValueConverterImpl; import javax.annotation.PostConstruct; import java.util.ArrayList; @@ -65,32 +68,36 @@ import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandle import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.GET_TYPE_OPER_DISCOVER; import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.GET_TYPE_OPER_OBSERVE; import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.GET_TYPE_OPER_READ; -import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.PUT_TYPE_OPER_WRITE_ATTRIBUTES; -import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.PUT_TYPE_OPER_WRITE_UPDATE; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LOG_LW2M_ERROR; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LOG_LW2M_INFO; import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.POST_TYPE_OPER_EXECUTE; import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.POST_TYPE_OPER_OBSERVE_CANCEL; import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.POST_TYPE_OPER_WRITE_REPLACE; -import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LOG_LW2M_ERROR; -import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LOG_LW2M_INFO; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.PUT_TYPE_OPER_WRITE_ATTRIBUTES; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.PUT_TYPE_OPER_WRITE_UPDATE; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.RESPONSE_CHANNEL; @Slf4j @Service("LwM2MTransportRequest") @ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' ) || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") public class LwM2MTransportRequest { - private final ExecutorService executorService; - private static final String RESPONSE_CHANNEL = "THINGSBOARD_RESP"; + private ExecutorService executorResponse; + private ExecutorService executorResponseError; + private LwM2mValueConverterImpl converter; @Autowired - LwM2MTransportService service; - - public LwM2MTransportRequest() { - executorService = Executors.newCachedThreadPool( - new NamedThreadFactory(String.format("LwM2M %s channel response", RESPONSE_CHANNEL))); - } + LwM2MTransportServiceImpl service; + @Autowired + public LwM2MTransportContextServer context; @PostConstruct public void init() { + this.converter = LwM2mValueConverterImpl.getInstance(); + executorResponse = Executors.newFixedThreadPool(this.context.getCtxServer().getRequestPoolSize(), + new NamedThreadFactory(String.format("LwM2M %s channel response", RESPONSE_CHANNEL))); + executorResponseError = Executors.newFixedThreadPool(this.context.getCtxServer().getRequestErrorPoolSize(), + new NamedThreadFactory(String.format("LwM2M %s channel response Error", RESPONSE_CHANNEL))); } public Collection doGetRegistrations(LeshanServer lwServer) { @@ -113,16 +120,13 @@ public class LwM2MTransportRequest { * @param lwM2MClient * @param observation */ - public void sendAllRequest(LeshanServer lwServer, Registration registration, String target, String typeOper, - String contentFormatParam, LwM2MClient lwM2MClient, Observation observation, Object params, long timeoutInMs) { - ResultIds resultIds = new ResultIds(target); + public void sendAllRequest(LeshanServer lwServer, Registration registration, String target, String typeOper, String contentFormatParam, + LwM2MClient lwM2MClient, Observation observation, Object params, long timeoutInMs, boolean isDelayedUpdate) { + LwM2mPath resultIds = new LwM2mPath(target); if (registration != null && resultIds.getObjectId() >= 0) { DownlinkRequest request = null; ContentFormat contentFormat = contentFormatParam != null ? ContentFormat.fromName(contentFormatParam.toUpperCase()) : null; - ResourceModel resource = (resultIds.resourceId >= 0) ? (lwM2MClient != null) ? - lwM2MClient.getModelObjects().get(resultIds.getObjectId()).getObjectModel().resources.get(resultIds.resourceId) : null : null; - ResourceModel.Type resType = (resource == null) ? null : resource.type; - boolean resMultiple = (resource == null) ? false : resource.multiple; + ResourceModel resource = service.context.getCtxServer().getResourceModel(registration, resultIds); timeoutInMs = timeoutInMs > 0 ? timeoutInMs : DEFAULT_TIMEOUT; switch (typeOper) { case GET_TYPE_OPER_READ: @@ -132,10 +136,10 @@ public class LwM2MTransportRequest { request = new DiscoverRequest(target); break; case GET_TYPE_OPER_OBSERVE: - if (resultIds.getResourceId() >= 0) { - request = new ObserveRequest(resultIds.getObjectId(), resultIds.getInstanceId(), resultIds.getResourceId()); - } else if (resultIds.getInstanceId() >= 0) { - request = new ObserveRequest(resultIds.getObjectId(), resultIds.getInstanceId()); + if (resultIds.isResource()) { + request = new ObserveRequest(resultIds.getObjectId(), resultIds.getObjectInstanceId(), resultIds.getResourceId()); + } else if (resultIds.isObjectInstance()) { + request = new ObserveRequest(resultIds.getObjectId(), resultIds.getObjectInstanceId()); } else if (resultIds.getObjectId() >= 0) { request = new ObserveRequest(resultIds.getObjectId()); } @@ -144,27 +148,30 @@ public class LwM2MTransportRequest { request = new CancelObservationRequest(observation); break; case POST_TYPE_OPER_EXECUTE: - if (params != null && !resMultiple) { - request = new ExecuteRequest(target, LwM2MTransportHandler.getValueTypeToString(params, resType)); + if (params != null && resource != null && !resource.multiple) { + request = new ExecuteRequest(target, (String) this.converter.convertValue(params, resource.type, ResourceModel.Type.STRING, resultIds)); } else { request = new ExecuteRequest(target); } break; case POST_TYPE_OPER_WRITE_REPLACE: // Request to write a String Single-Instance Resource using the TLV content format. - if (contentFormat.equals(ContentFormat.TLV) && !resMultiple) { - request = this.getWriteRequestSingleResource(null, resultIds.getObjectId(), resultIds.getInstanceId(), resultIds.getResourceId(), params, resType); - } - // Mode.REPLACE && Request to write a String Single-Instance Resource using the given content format (TEXT, TLV, JSON) - else if (!contentFormat.equals(ContentFormat.TLV) && !resMultiple) { - request = this.getWriteRequestSingleResource(contentFormat, resultIds.getObjectId(), resultIds.getInstanceId(), resultIds.getResourceId(), params, resType); + if (resource != null) { + if (contentFormat.equals(ContentFormat.TLV) && !resource.multiple) { + request = this.getWriteRequestSingleResource(null, resultIds.getObjectId(), resultIds.getObjectInstanceId(), resultIds.getResourceId(), params, resource.type, registration); + } + // Mode.REPLACE && Request to write a String Single-Instance Resource using the given content format (TEXT, TLV, JSON) + else if (!contentFormat.equals(ContentFormat.TLV) && !resource.multiple) { + request = this.getWriteRequestSingleResource(contentFormat, resultIds.getObjectId(), resultIds.getObjectInstanceId(), resultIds.getResourceId(), params, resource.type, registration); + } } break; case PUT_TYPE_OPER_WRITE_UPDATE: if (resultIds.getResourceId() >= 0) { ResourceModel resourceModel = lwServer.getModelProvider().getObjectModel(registration).getObjectModel(resultIds.getObjectId()).resources.get(resultIds.getResourceId()); ResourceModel.Type typeRes = resourceModel.type; -// request = getWriteRequestResource(resultIds.getObjectId(), resultIds.getInstanceId(), resultIds.getResourceId(), params, typeRes); + LwM2mNode node = LwM2mSingleResource.newStringResource(resultIds.getResourceId(), (String) this.converter.convertValue(params, resource.type, ResourceModel.Type.STRING, resultIds)); + request = new WriteRequest(WriteRequest.Mode.UPDATE, contentFormat, target, node); } break; case PUT_TYPE_OPER_WRITE_ATTRIBUTES: @@ -202,55 +209,76 @@ public class LwM2MTransportRequest { Attribute pmin = new Attribute(MINIMUM_PERIOD, Integer.toUnsignedLong(Integer.valueOf("1"))); Attribute[] attrs = {pmin}; AttributeSet attrSet = new AttributeSet(attrs); - if (resultIds.getResourceId() >= 0) { - request = new WriteAttributesRequest(resultIds.getObjectId(), resultIds.getInstanceId(), resultIds.getResourceId(), attrSet); - } else if (resultIds.getInstanceId() >= 0) { - request = new WriteAttributesRequest(resultIds.getObjectId(), resultIds.getInstanceId(), attrSet); + if (resultIds.isResource()) { + request = new WriteAttributesRequest(resultIds.getObjectId(), resultIds.getObjectInstanceId(), resultIds.getResourceId(), attrSet); + } else if (resultIds.isObjectInstance()) { + request = new WriteAttributesRequest(resultIds.getObjectId(), resultIds.getObjectInstanceId(), attrSet); } else if (resultIds.getObjectId() >= 0) { request = new WriteAttributesRequest(resultIds.getObjectId(), attrSet); } break; default: } - if (request != null) sendRequest(lwServer, registration, request, lwM2MClient, timeoutInMs); + + if (request != null) { + this.sendRequest(lwServer, registration, request, lwM2MClient, timeoutInMs, isDelayedUpdate); + } else if (isDelayedUpdate) { + String msg = String.format(LOG_LW2M_ERROR + ": sendRequest: Resource path - %s msg No SendRequest to Client", target); + service.sentLogsToThingsboard(msg, registration); + log.error("[{}] - [{}] No SendRequest", target); + this.handleResponseError(registration, target, lwM2MClient, isDelayedUpdate); + + } } } /** * - * @param lwServer - * @param registration - * @param request - * @param lwM2MClient - * @param timeoutInMs + * @param lwServer - + * @param registration - + * @param request - + * @param lwM2MClient - + * @param timeoutInMs - */ - private void sendRequest(LeshanServer lwServer, Registration registration, DownlinkRequest request, LwM2MClient lwM2MClient, long timeoutInMs) { + + private void sendRequest(LeshanServer lwServer, Registration registration, DownlinkRequest request, LwM2MClient lwM2MClient, long timeoutInMs, boolean isDelayedUpdate) { lwServer.send(registration, request, timeoutInMs, (ResponseCallback) response -> { - if (isSuccess(((Response)response.getCoapResponse()).getCode())) { - this.handleResponse(registration, request.getPath().toString(), response, request, lwM2MClient); + if (isSuccess(((Response) response.getCoapResponse()).getCode())) { + this.handleResponse(registration, request.getPath().toString(), response, request, lwM2MClient, isDelayedUpdate); if (request instanceof WriteRequest && ((WriteRequest) request).isReplaceRequest()) { - String msg = String.format(LOG_LW2M_INFO + " sendRequest Replace: CoapCde - %s Lwm2m code - %d name - %s Resource path - %s value - %s SendRequest to Client", - ((Response)response.getCoapResponse()).getCode(), response.getCode().getCode(), response.getCode().getName(), request.getPath().toString(), - ((LwM2mSingleResource)((WriteRequest) request).getNode()).getValue().toString()); - service.sentLogsToThingsboard(msg, registration.getId()); - log.info("[{}] - [{}] [{}] [{}] Update SendRequest", ((Response)response.getCoapResponse()).getCode(), response.getCode(), request.getPath().toString(), ((LwM2mSingleResource)((WriteRequest) request).getNode()).getValue()); + String delayedUpdateStr = ""; + if (isDelayedUpdate) { + delayedUpdateStr = " (delayedUpdate) "; + } + String msg = String.format(LOG_LW2M_INFO + ": sendRequest Replace%s: CoapCde - %s Lwm2m code - %d name - %s Resource path - %s value - %s SendRequest to Client", + delayedUpdateStr, ((Response) response.getCoapResponse()).getCode(), response.getCode().getCode(), response.getCode().getName(), request.getPath().toString(), + ((LwM2mSingleResource) ((WriteRequest) request).getNode()).getValue().toString()); + service.sentLogsToThingsboard(msg, registration); + log.info("[{}] - [{}] [{}] [{}] Update SendRequest[{}]", ((Response) response.getCoapResponse()).getCode(), response.getCode(), request.getPath().toString(), + ((LwM2mSingleResource) ((WriteRequest) request).getNode()).getValue(), delayedUpdateStr); + } + } else { + String msg = String.format(LOG_LW2M_ERROR + ": sendRequest: CoapCode - %s Lwm2m code - %d name - %s Resource path - %s SendRequest to Client", + ((Response) response.getCoapResponse()).getCode(), response.getCode().getCode(), response.getCode().getName(), request.getPath().toString()); + service.sentLogsToThingsboard(msg, registration); + log.error("[{}] - [{}] [{}] error SendRequest", ((Response) response.getCoapResponse()).getCode(), response.getCode(), request.getPath().toString()); + if (request instanceof WriteRequest && ((WriteRequest) request).isReplaceRequest() && isDelayedUpdate) { + this.handleResponseError(registration, request.getPath().toString(), lwM2MClient, isDelayedUpdate); } } - else { - String msg = String.format(LOG_LW2M_ERROR + " sendRequest: CoapCde - %s Lwm2m code - %d name - %s Resource path - %s SendRequest to Client", - ((Response)response.getCoapResponse()).getCode(), response.getCode().getCode(), response.getCode().getName(), request.getPath().toString()); - service.sentLogsToThingsboard(msg, registration.getId()); - log.error("[{}] - [{}] [{}] error SendRequest", ((Response)response.getCoapResponse()).getCode(), response.getCode(), request.getPath().toString()); - } + }, e -> { - String msg = String.format(LOG_LW2M_ERROR + " sendRequest: Resource path - %s msg error - %s SendRequest to Client", + String msg = String.format(LOG_LW2M_ERROR + ": sendRequest: Resource path - %s msg error - %s SendRequest to Client", request.getPath().toString(), e.toString()); - service.sentLogsToThingsboard(msg, registration.getId()); - log.error("[{}] - [{}] error SendRequest", request.getPath().toString(), e.toString()); + service.sentLogsToThingsboard(msg, registration); + log.error("[{}] - [{}] error SendRequest", request.getPath().toString(), e.toString()); + if (request instanceof WriteRequest && ((WriteRequest) request).isReplaceRequest() && isDelayedUpdate) { + this.handleResponseError(registration, request.getPath().toString(), lwM2MClient, isDelayedUpdate); + } }); } - private WriteRequest getWriteRequestSingleResource(ContentFormat contentFormat, Integer objectId, Integer instanceId, Integer resourceId, Object value, ResourceModel.Type type) { + private WriteRequest getWriteRequestSingleResource(ContentFormat contentFormat, Integer objectId, Integer instanceId, Integer resourceId, Object value, ResourceModel.Type type, Registration registration) { try { switch (type) { case STRING: // String @@ -264,29 +292,38 @@ public class LwM2MTransportRequest { case FLOAT: // Double return (contentFormat == null) ? new WriteRequest(objectId, instanceId, resourceId, Double.valueOf(value.toString())) : new WriteRequest(contentFormat, objectId, instanceId, resourceId, Double.valueOf(value.toString())); case TIME: // Date - return (contentFormat == null) ? new WriteRequest(objectId, instanceId, resourceId, new Date((Long) Integer.toUnsignedLong(Integer.valueOf(value.toString())))) : new WriteRequest(contentFormat, objectId, instanceId, resourceId, new Date((Long) Integer.toUnsignedLong(Integer.valueOf(value.toString())))); + return (contentFormat == null) ? new WriteRequest(objectId, instanceId, resourceId, new Date(Long.decode(value.toString()))) : new WriteRequest(contentFormat, objectId, instanceId, resourceId, new Date((Long) Integer.toUnsignedLong(Integer.valueOf(value.toString())))); case OPAQUE: // byte[] value, base64 return (contentFormat == null) ? new WriteRequest(objectId, instanceId, resourceId, Hex.decodeHex(value.toString().toCharArray())) : new WriteRequest(contentFormat, objectId, instanceId, resourceId, Hex.decodeHex(value.toString().toCharArray())); default: } return null; } catch (NumberFormatException e) { - String patn = "/" + objectId + "/" + instanceId + "/" + resourceId; - log.error("Path: [{}] type: [{}] value: [{}] errorMsg: [{}]]", patn, type, value, e.toString()); - return null; + String patn = "/" + objectId + "/" + instanceId + "/" + resourceId; + String msg = String.format(LOG_LW2M_ERROR + ": NumberFormatException: Resource path - %s type - %s value - %s msg error - %s SendRequest to Client", + patn, type, value, e.toString()); + service.sentLogsToThingsboard(msg, registration); + log.error("Path: [{}] type: [{}] value: [{}] errorMsg: [{}]]", patn, type, value, e.toString()); + return null; } } - private void handleResponse(Registration registration, final String path, LwM2mResponse response, DownlinkRequest request, LwM2MClient lwM2MClient) { - executorService.submit(new Runnable() { - @Override - public void run() { + private void handleResponse(Registration registration, final String path, LwM2mResponse response, DownlinkRequest request, LwM2MClient lwM2MClient, boolean isDelayedUpdate) { + executorResponse.submit(() -> { + try { + sendResponse(registration, path, response, request, lwM2MClient, isDelayedUpdate); + } catch (Exception e) { + log.error("[{}] endpoint [{}] path [{}] Exception Unable to after send response.", registration.getEndpoint(), path, e); + } + }); + } - try { - sendResponse(registration, path, response, request, lwM2MClient); - } catch (RuntimeException t) { - log.error("[{}] endpoint [{}] path [{}] error Unable to after send response.", registration.getEndpoint(), path, t.toString()); - } + private void handleResponseError(Registration registration, final String path, LwM2MClient lwM2MClient, boolean isDelayedUpdate) { + executorResponseError.submit(() -> { + try { + if (isDelayedUpdate) lwM2MClient.onSuccessOrErrorDelayedRequests(path); + } catch (RuntimeException t) { + log.error("[{}] endpoint [{}] path [{}] RuntimeException Unable to after send response.", registration.getEndpoint(), path, t); } }); } @@ -298,7 +335,7 @@ public class LwM2MTransportRequest { * @param response - * @param lwM2MClient - */ - private void sendResponse(Registration registration, String path, LwM2mResponse response, DownlinkRequest request, LwM2MClient lwM2MClient) { + private void sendResponse(Registration registration, String path, LwM2mResponse response, DownlinkRequest request, LwM2MClient lwM2MClient, boolean isDelayedUpdate) { if (response instanceof ObserveResponse) { service.onObservationResponse(registration, path, (ReadResponse) response); } else if (response instanceof CancelObservationResponse) { @@ -329,7 +366,7 @@ public class LwM2MTransportRequest { log.info("[{}] Path [{}] WriteAttributesResponse 8_Send", path, response); } else if (response instanceof WriteResponse) { log.info("[{}] Path [{}] WriteAttributesResponse 9_Send", path, response); - service.onAttributeUpdateOk(registration, path, (WriteRequest) request); + service.onAttributeUpdateOk(registration, path, (WriteRequest) request, isDelayedUpdate); } } } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServerConfiguration.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServerConfiguration.java index 2725e80e2b..c6ce086446 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServerConfiguration.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServerConfiguration.java @@ -20,10 +20,16 @@ import org.eclipse.californium.scandium.config.DtlsConnectorConfig; import org.eclipse.leshan.core.node.codec.DefaultLwM2mNodeDecoder; import org.eclipse.leshan.core.node.codec.DefaultLwM2mNodeEncoder; import org.eclipse.leshan.core.node.codec.LwM2mNodeDecoder; +import org.eclipse.leshan.core.util.Hex; import org.eclipse.leshan.server.californium.LeshanServer; import org.eclipse.leshan.server.californium.LeshanServerBuilder; import org.eclipse.leshan.server.model.LwM2mModelProvider; import org.eclipse.leshan.server.model.VersionedModelProvider; +import org.eclipse.leshan.server.redis.RedisRegistrationStore; +import org.eclipse.leshan.server.redis.RedisSecurityStore; +import org.eclipse.leshan.server.security.DefaultAuthorizer; +import org.eclipse.leshan.server.security.EditableSecurityStore; +import org.eclipse.leshan.server.security.SecurityChecker; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.annotation.Bean; @@ -31,11 +37,36 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode; -import org.thingsboard.server.transport.lwm2m.server.secure.LwM2MSetSecurityStoreServer; import org.thingsboard.server.transport.lwm2m.server.secure.LwM2mInMemorySecurityStore; import org.thingsboard.server.transport.lwm2m.utils.LwM2mValueConverterImpl; -import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.X509; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.util.Pool; + +import java.math.BigInteger; +import java.net.URI; +import java.net.URISyntaxException; +import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.KeyStoreException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.security.interfaces.ECPublicKey; +import java.security.spec.ECGenParameterSpec; +import java.security.spec.ECParameterSpec; +import java.security.spec.ECPoint; +import java.security.spec.ECPrivateKeySpec; +import java.security.spec.ECPublicKeySpec; +import java.security.spec.KeySpec; +import java.util.Arrays; + +import static org.eclipse.californium.scandium.dtls.cipher.CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256; +import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.PSK; import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.RPK; +import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.X509; import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.getCoapConfig; @@ -45,6 +76,8 @@ import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandle @Configuration("LwM2MTransportServerConfiguration") @ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' ) || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") public class LwM2MTransportServerConfiguration { + private PublicKey publicKey; + private PrivateKey privateKey; @Autowired private LwM2MTransportContextServer context; @@ -53,50 +86,257 @@ public class LwM2MTransportServerConfiguration { private LwM2mInMemorySecurityStore lwM2mInMemorySecurityStore; @Primary - @Bean(name = "LeshanServerCert") - public LeshanServer getLeshanServerCert() { - log.info("Starting LwM2M transport ServerCert... PostConstruct"); - return getLeshanServer(this.context.getCtxServer().getServerPortCert(), this.context.getCtxServer().getServerSecurePortCert(), X509); + @Bean(name = "leshanServerPsk") + @ConditionalOnExpression("('${transport.lwm2m.server.secure.start_psk:false}'=='true')") + public LeshanServer getLeshanServerPsk() { + log.info("Starting LwM2M transport ServerPsk... PostConstruct"); + return getLeshanServer(this.context.getCtxServer().getServerPortNoSecPsk(), this.context.getCtxServer().getServerPortPsk(), PSK); } - @Bean(name = "leshanServerNoSecPskRpk") - public LeshanServer getLeshanServerNoSecPskRpk() { - log.info("Starting LwM2M transport ServerNoSecPskRpk... PostConstruct"); - return getLeshanServer(this.context.getCtxServer().getServerPort(), this.context.getCtxServer().getServerSecurePort(), RPK); + @Bean(name = "leshanServerRpk") + @ConditionalOnExpression("('${transport.lwm2m.server.secure.start_rpk:false}'=='true')") + public LeshanServer getLeshanServerRpk() { + log.info("Starting LwM2M transport ServerRpk... PostConstruct"); + return getLeshanServer(this.context.getCtxServer().getServerPortNoSecRpk(), this.context.getCtxServer().getServerPortRpk(), RPK); } - private LeshanServer getLeshanServer(Integer serverPort, Integer serverSecurePort, LwM2MSecurityMode dtlsMode) { + @Bean(name = "leshanServerX509") + @ConditionalOnExpression("('${transport.lwm2m.server.secure.start_x509:false}'=='true')") + public LeshanServer getLeshanServerX509() { + log.info("Starting LwM2M transport ServerX509... PostConstruct"); + return getLeshanServer(this.context.getCtxServer().getServerPortNoSecX509(), this.context.getCtxServer().getServerPortX509(), X509); + } + private LeshanServer getLeshanServer(Integer serverPortNoSec, Integer serverSecurePort, LwM2MSecurityMode dtlsMode) { LeshanServerBuilder builder = new LeshanServerBuilder(); - builder.setLocalAddress(this.context.getCtxServer().getServerHost(), serverPort); + builder.setLocalAddress(this.context.getCtxServer().getServerHost(), serverPortNoSec); builder.setLocalSecureAddress(this.context.getCtxServer().getServerSecureHost(), serverSecurePort); builder.setEncoder(new DefaultLwM2mNodeEncoder()); LwM2mNodeDecoder decoder = new DefaultLwM2mNodeDecoder(); builder.setDecoder(decoder); - builder.setEncoder(new DefaultLwM2mNodeEncoder(new LwM2mValueConverterImpl())); + builder.setEncoder(new DefaultLwM2mNodeEncoder(LwM2mValueConverterImpl.getInstance())); /** Create CoAP Config */ - builder.setCoapConfig(getCoapConfig()); + builder.setCoapConfig(getCoapConfig(serverPortNoSec, serverSecurePort)); /** Define model provider (Create Models )*/ LwM2mModelProvider modelProvider = new VersionedModelProvider(this.context.getCtxServer().getModelsValue()); builder.setObjectModelProvider(modelProvider); + /** Create DTLS security mode + * There can be only one DTLS security mode + */ + this.LwM2MSetSecurityStoreServer(builder, dtlsMode); + /** Create DTLS Config */ DtlsConnectorConfig.Builder dtlsConfig = new DtlsConnectorConfig.Builder(); - dtlsConfig.setRecommendedCipherSuitesOnly(this.context.getCtxServer().isSupportDeprecatedCiphersEnable()); + if (dtlsMode==PSK) { + dtlsConfig.setRecommendedCipherSuitesOnly(this.context.getCtxServer().isRecommendedCiphers()); + dtlsConfig.setRecommendedSupportedGroupsOnly(this.context.getCtxServer().isRecommendedSupportedGroups()); + dtlsConfig.setSupportedCipherSuites(TLS_PSK_WITH_AES_128_CBC_SHA256); + } + else { + dtlsConfig.setRecommendedSupportedGroupsOnly(!this.context.getCtxServer().isRecommendedSupportedGroups()); + dtlsConfig.setRecommendedCipherSuitesOnly(!this.context.getCtxServer().isRecommendedCiphers()); + } /** Set DTLS Config */ builder.setDtlsConfig(dtlsConfig); /** Use a magic converter to support bad type send by the UI. */ - builder.setEncoder(new DefaultLwM2mNodeEncoder(new LwM2mValueConverterImpl())); + builder.setEncoder(new DefaultLwM2mNodeEncoder(LwM2mValueConverterImpl.getInstance())); - /** Create DTLS security mode - * There can be only one DTLS security mode - */ - new LwM2MSetSecurityStoreServer(builder, context, lwM2mInMemorySecurityStore, dtlsMode); /** Create LWM2M server */ return builder.build(); } + + private void LwM2MSetSecurityStoreServer(LeshanServerBuilder builder, LwM2MSecurityMode dtlsMode) { + /** Set securityStore with new registrationStore */ + EditableSecurityStore securityStore = lwM2mInMemorySecurityStore; + switch (dtlsMode) { + /** Use PSK only */ + case PSK: + generatePSK_RPK(); + infoParamsPSK(); + break; + /** Use RPK only */ + case RPK: + generatePSK_RPK(); + if (this.publicKey != null && this.publicKey.getEncoded().length > 0 && + this.privateKey != null && this.privateKey.getEncoded().length > 0) { + builder.setPublicKey(this.publicKey); + builder.setPrivateKey(this.privateKey); + infoParamsRPK(); + } + break; + /** Use x509 only */ + case X509: + setServerWithX509Cert(builder); + break; + /** No security */ + case NO_SEC: + builder.setTrustedCertificates(new X509Certificate[0]); + break; + /** Use x509 with EST */ + case X509_EST: + // TODO support sentinel pool and make pool configurable + break; + case REDIS: + /** + * Set securityStore with new registrationStore (if use redis store) + * Connect to redis + */ + Pool jedis = null; + try { + jedis = new JedisPool(new URI(this.context.getCtxServer().getRedisUrl())); + securityStore = new RedisSecurityStore(jedis); + builder.setRegistrationStore(new RedisRegistrationStore(jedis)); + } catch (URISyntaxException e) { + log.error("", e); + } + break; + default: + } + + /** Set securityStore with registrationStore (if x509)*/ + if (dtlsMode == X509) { + builder.setAuthorizer(new DefaultAuthorizer(securityStore, new SecurityChecker() { + @Override + protected boolean matchX509Identity(String endpoint, String receivedX509CommonName, + String expectedX509CommonName) { + return endpoint.startsWith(expectedX509CommonName); + } + })); + } + + /** Set securityStore with new registrationStore */ + builder.setSecurityStore(securityStore); + } + + private void generatePSK_RPK() { + try { + /** Get Elliptic Curve Parameter spec for secp256r1 */ + AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC"); + algoParameters.init(new ECGenParameterSpec("secp256r1")); + ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class); + if (this.context.getCtxServer().getServerPublicX() != null && !this.context.getCtxServer().getServerPublicX().isEmpty() && this.context.getCtxServer().getServerPublicY() != null && !this.context.getCtxServer().getServerPublicY().isEmpty()) { + /** Get point values */ + byte[] publicX = Hex.decodeHex(this.context.getCtxServer().getServerPublicX().toCharArray()); + byte[] publicY = Hex.decodeHex(this.context.getCtxServer().getServerPublicY().toCharArray()); + /** Create key specs */ + KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), + parameterSpec); + /** Get keys */ + this.publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec); + } + if (this.context.getCtxServer().getServerPrivateS() != null && !this.context.getCtxServer().getServerPrivateS().isEmpty()) { + /** Get point values */ + byte[] privateS = Hex.decodeHex(this.context.getCtxServer().getServerPrivateS().toCharArray()); + /** Create key specs */ + KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec); + /** Get keys */ + this.privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec); + } + } catch (GeneralSecurityException | IllegalArgumentException e) { + log.error("[{}] Failed generate Server PSK/RPK", e.getMessage()); + throw new RuntimeException(e); + } + } + + private void infoParamsPSK() { + log.info("\nServer uses PSK -> private key : \n security key : [{}] \n serverSecureURI : [{}]", + Hex.encodeHexString(this.privateKey.getEncoded()), + this.context.getCtxServer().getServerSecureHost() + ":" + Integer.toString(this.context.getCtxServer().getServerPortPsk())); + } + + private void infoParamsRPK() { + if (this.publicKey instanceof ECPublicKey) { + /** Get x coordinate */ + byte[] x = ((ECPublicKey) this.publicKey).getW().getAffineX().toByteArray(); + if (x[0] == 0) + x = Arrays.copyOfRange(x, 1, x.length); + + /** Get Y coordinate */ + byte[] y = ((ECPublicKey) this.publicKey).getW().getAffineY().toByteArray(); + if (y[0] == 0) + y = Arrays.copyOfRange(y, 1, y.length); + + /** Get Curves params */ + String params = ((ECPublicKey) this.publicKey).getParams().toString(); + log.info( + " \nServer uses RPK : \n Elliptic Curve parameters : [{}] \n Public x coord : [{}] \n Public y coord : [{}] \n Public Key (Hex): [{}] \n Private Key (Hex): [{}]", + params, Hex.encodeHexString(x), Hex.encodeHexString(y), + Hex.encodeHexString(this.publicKey.getEncoded()), + Hex.encodeHexString(this.privateKey.getEncoded())); + } else { + throw new IllegalStateException("Unsupported Public Key Format (only ECPublicKey supported)."); + } + } + + + private void setServerWithX509Cert(LeshanServerBuilder builder) { + try { + if (this.context.getCtxServer().getKeyStoreValue() != null) { + setBuilderX509(builder); + X509Certificate rootCAX509Cert = (X509Certificate) this.context.getCtxServer().getKeyStoreValue().getCertificate(this.context.getCtxServer().getRootAlias()); + if (rootCAX509Cert != null) { + X509Certificate[] trustedCertificates = new X509Certificate[1]; + trustedCertificates[0] = rootCAX509Cert; + builder.setTrustedCertificates(trustedCertificates); + } else { + /** by default trust all */ + builder.setTrustedCertificates(new X509Certificate[0]); + } + } else { + /** by default trust all */ + builder.setTrustedCertificates(new X509Certificate[0]); + log.error("Unable to load X509 files for LWM2MServer"); + } + } catch (KeyStoreException ex) { + log.error("[{}] Unable to load X509 files server", ex.getMessage()); + } + } + + private void setBuilderX509(LeshanServerBuilder builder) { + /** + * For deb => KeyStorePathFile == yml or commandline: KEY_STORE_PATH_FILE + * For idea => KeyStorePathResource == common/transport/lwm2m/src/main/resources/credentials: in LwM2MTransportContextServer: credentials/serverKeyStore.jks + */ + try { + X509Certificate serverCertificate = (X509Certificate) this.context.getCtxServer().getKeyStoreValue().getCertificate(this.context.getCtxServer().getServerAlias()); + PrivateKey privateKey = (PrivateKey) this.context.getCtxServer().getKeyStoreValue().getKey(this.context.getCtxServer().getServerAlias(), this.context.getCtxServer().getKeyStorePasswordServer() == null ? null : this.context.getCtxServer().getKeyStorePasswordServer().toCharArray()); + builder.setPrivateKey(privateKey); + builder.setCertificateChain(new X509Certificate[]{serverCertificate}); + this.infoParamsX509(serverCertificate, privateKey); + } catch (Exception ex) { + log.error("[{}] Unable to load KeyStore files server", ex.getMessage()); + } +// /** +// * For deb => KeyStorePathFile == yml or commandline: KEY_STORE_PATH_FILE +// * For idea => KeyStorePathResource == common/transport/lwm2m/src/main/resources/credentials: in LwM2MTransportContextServer: credentials/serverKeyStore.jks +// */ +// try { +// X509Certificate serverCertificate = (X509Certificate) this.context.getCtxServer().getKeyStoreValue().getCertificate(this.context.getCtxServer().getServerPrivateS()); +// this.privateKey = (PrivateKey) this.context.getCtxServer().getKeyStoreValue().getKey(this.context.getCtxServer().getServerAlias(), this.context.getCtxServer().getKeyStorePasswordServer() == null ? null : this.context.getCtxServer().getKeyStorePasswordServer().toCharArray()); +// if (this.privateKey != null && this.privateKey.getEncoded().length > 0) { +// builder.setPrivateKey(this.privateKey); +// } +// if (serverCertificate != null) { +// builder.setCertificateChain(new X509Certificate[]{serverCertificate}); +// this.infoParamsX509(serverCertificate); +// } +// } catch (Exception ex) { +// log.error("[{}] Unable to load KeyStore files server", ex.getMessage()); +// } + } + + private void infoParamsX509(X509Certificate certificate, PrivateKey privateKey) { + try { + log.info("Server uses X509 : \n X509 Certificate (Hex): [{}] \n Private Key (Hex): [{}]", + Hex.encodeHexString(certificate.getEncoded()), + Hex.encodeHexString(privateKey.getEncoded())); + } catch (CertificateEncodingException e) { + log.error("", e); + } + } } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServerInitializer.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServerInitializer.java index 4a43407a73..74a37938b3 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServerInitializer.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServerInitializer.java @@ -20,24 +20,32 @@ import org.eclipse.leshan.server.californium.LeshanServer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; import org.thingsboard.server.transport.lwm2m.secure.LWM2MGenerationPSkRPkECC; -import org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode; + import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Slf4j -@Service("LwM2MTransportServerInitializer") +@Component("LwM2MTransportServerInitializer") @ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' ) || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") public class LwM2MTransportServerInitializer { - @Autowired - @Qualifier("LeshanServerCert") - private LeshanServer lhServerCert; @Autowired - @Qualifier("leshanServerNoSecPskRpk") - private LeshanServer lhServerNoSecPskRpk; + private LwM2MTransportServiceImpl service; + + @Autowired(required = false) + @Qualifier("leshanServerX509") + private LeshanServer lhServerX509; + + @Autowired(required = false) + @Qualifier("leshanServerPsk") + private LeshanServer lhServerPsk; + + @Autowired(required = false) + @Qualifier("leshanServerRpk") + private LeshanServer lhServerRpk; @Autowired private LwM2MTransportContextServer context; @@ -45,28 +53,47 @@ public class LwM2MTransportServerInitializer { @PostConstruct public void init() { if (this.context.getCtxServer().getEnableGenPskRpk()) new LWM2MGenerationPSkRPkECC(); - if (this.context.getCtxServer().isServerStartAll()) { - this.lhServerCert.start(); - this.lhServerNoSecPskRpk.start(); + if (this.context.getCtxServer().isServerStartPsk()) { + this.startLhServerPsk(); + } + if (this.context.getCtxServer().isServerStartRpk()) { + this.startLhServerRpk(); } - else { - if (this.context.getCtxServer().getServerDtlsMode() == LwM2MSecurityMode.X509.code) { - this.lhServerCert.start(); - } - else { - this.lhServerNoSecPskRpk.start(); - } + if (this.context.getCtxServer().isServerStartX509()) { + this.startLhServerX509(); } } + private void startLhServerPsk() { + this.lhServerPsk.start(); + LwM2mServerListener lhServerPskListener = new LwM2mServerListener(this.lhServerPsk, service); + this.lhServerPsk.getRegistrationService().addListener(lhServerPskListener.registrationListener); + this.lhServerPsk.getPresenceService().addListener(lhServerPskListener.presenceListener); + this.lhServerPsk.getObservationService().addListener(lhServerPskListener.observationListener); + } + + private void startLhServerRpk() { + this.lhServerRpk.start(); + LwM2mServerListener lhServerRpkListener = new LwM2mServerListener(this.lhServerRpk, service); + this.lhServerRpk.getRegistrationService().addListener(lhServerRpkListener.registrationListener); + this.lhServerRpk.getPresenceService().addListener(lhServerRpkListener.presenceListener); + this.lhServerRpk.getObservationService().addListener(lhServerRpkListener.observationListener); + } + + private void startLhServerX509() { + this.lhServerX509.start(); + LwM2mServerListener lhServerCertListener = new LwM2mServerListener(this.lhServerX509, service); + this.lhServerX509.getRegistrationService().addListener(lhServerCertListener.registrationListener); + this.lhServerX509.getPresenceService().addListener(lhServerCertListener.presenceListener); + this.lhServerX509.getObservationService().addListener(lhServerCertListener.observationListener); + } + @PreDestroy public void shutdown() { log.info("Stopping LwM2M transport Server!"); - try { - lhServerCert.destroy(); - lhServerNoSecPskRpk.destroy(); - } finally { - } + lhServerPsk.destroy(); + lhServerRpk.destroy(); + lhServerX509.destroy(); log.info("LwM2M transport Server stopped!"); } } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportService.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportService.java index 7ff68b928c..3b21e7003f 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportService.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportService.java @@ -15,985 +15,42 @@ */ package org.thingsboard.server.transport.lwm2m.server; -import com.google.gson.*; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; -import org.eclipse.leshan.core.model.ResourceModel; -import org.eclipse.leshan.core.node.LwM2mMultipleResource; -import org.eclipse.leshan.core.node.LwM2mObject; -import org.eclipse.leshan.core.node.LwM2mObjectInstance; -import org.eclipse.leshan.core.node.LwM2mSingleResource; -import org.eclipse.leshan.core.node.LwM2mResource; -import org.eclipse.leshan.core.node.LwM2mPath; import org.eclipse.leshan.core.observation.Observation; -import org.eclipse.leshan.core.request.ContentFormat; -import org.eclipse.leshan.core.request.WriteRequest; import org.eclipse.leshan.core.response.ReadResponse; -import org.eclipse.leshan.core.util.Hex; import org.eclipse.leshan.server.californium.LeshanServer; import org.eclipse.leshan.server.registration.Registration; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; -import org.thingsboard.server.common.transport.TransportService; -import org.thingsboard.server.common.transport.TransportServiceCallback; -import org.thingsboard.server.common.transport.adaptor.AdaptorException; -import org.thingsboard.server.common.transport.adaptor.JsonConverter; -import org.thingsboard.server.common.transport.service.DefaultTransportService; import org.thingsboard.server.gen.transport.TransportProtos; -import org.thingsboard.server.gen.transport.TransportProtos.ToTransportUpdateCredentialsProto; -import org.thingsboard.server.gen.transport.TransportProtos.SessionEvent; -import org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto; -import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceCredentialsResponseMsg; -import org.thingsboard.server.gen.transport.TransportProtos.PostTelemetryMsg; -import org.thingsboard.server.gen.transport.TransportProtos.PostAttributeMsg; -import org.thingsboard.server.transport.lwm2m.server.adaptors.LwM2MJsonAdaptor; -import org.thingsboard.server.transport.lwm2m.server.client.AttrTelemetryObserveValue; -import org.thingsboard.server.transport.lwm2m.server.client.LwM2MClient; -import org.thingsboard.server.transport.lwm2m.server.client.ModelObject; -import org.thingsboard.server.transport.lwm2m.server.client.ResultsAnalyzerParameters; -import org.thingsboard.server.transport.lwm2m.server.client.ResourceValue; -import org.thingsboard.server.transport.lwm2m.server.secure.LwM2mInMemorySecurityStore; -import javax.annotation.PostConstruct; import java.util.Collection; -import java.util.UUID; -import java.util.Random; -import java.util.Map; -import java.util.HashMap; -import java.util.Arrays; -import java.util.Set; -import java.util.HashSet; -import java.util.NoSuchElementException; import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import static org.eclipse.leshan.core.model.ResourceModel.Type.OPAQUE; -import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.*; +public interface LwM2MTransportService { -@Slf4j -@Service("LwM2MTransportService") -@ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' ) || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") -public class LwM2MTransportService { + void onRegistered(LeshanServer lwServer, Registration registration, Collection previousObsersations); - @Autowired - private LwM2MJsonAdaptor adaptor; + void updatedReg(LeshanServer lwServer, Registration registration); - @Autowired - private TransportService transportService; + void unReg(LeshanServer lwServer, Registration registration, Collection observations); - @Autowired - public LwM2MTransportContextServer context; + void onSleepingDev(Registration registration); - @Autowired - private LwM2MTransportRequest lwM2MTransportRequest; + void setCancelObservations(LeshanServer lwServer, Registration registration); - @Autowired - LwM2mInMemorySecurityStore lwM2mInMemorySecurityStore; + void setCancelObservationRecourse(LeshanServer lwServer, Registration registration, String path); + void onObservationResponse(Registration registration, String path, ReadResponse response); - @PostConstruct - public void init() { - context.getScheduler().scheduleAtFixedRate(() -> checkInactivityAndReportActivity(), new Random().nextInt((int) context.getCtxServer().getSessionReportTimeout()), context.getCtxServer().getSessionReportTimeout(), TimeUnit.MILLISECONDS); - } + void onAttributeUpdate(TransportProtos.AttributeUpdateNotificationMsg msg, TransportProtos.SessionInfoProto sessionInfo); - /** - * Start registration device - * Create session: Map, LwM2MClient> - * 1. replaceNewRegistration -> (solving the problem of incorrect termination of the previous session with this endpoint) - * 1.1 When we initialize the registration, we register the session by endpoint. - * 1.2 If the server has incomplete requests (canceling the registration of the previous session), - * delete the previous session only by the previous registration.getId - * 1.2 Add Model (Entity) for client (from registration & observe) by registration.getId - * 1.2 Remove from sessions Model by enpPoint - * Next -> Create new LwM2MClient for current session -> setModelClient... - * - * @param lwServer - LeshanServer - * @param registration - Registration LwM2M Client - * @param previousObsersations - may be null - */ - public void onRegistered(LeshanServer lwServer, Registration registration, Collection previousObsersations) { - LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getlwM2MClient(lwServer, registration); - if (lwM2MClient != null) { - lwM2MClient.setLwM2MTransportService(this); - lwM2MClient.setLwM2MTransportService(this); - lwM2MClient.setSessionUuid(UUID.randomUUID()); - this.setLwM2MClient(lwServer, registration, lwM2MClient); - SessionInfoProto sessionInfo = this.getValidateSessionInfo(registration.getId()); - if (sessionInfo != null) { - lwM2MClient.setDeviceUuid(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB())); - lwM2MClient.setProfileUuid(new UUID(sessionInfo.getDeviceProfileIdMSB(), sessionInfo.getDeviceProfileIdLSB())); - lwM2MClient.setDeviceName(sessionInfo.getDeviceName()); - lwM2MClient.setDeviceProfileName(sessionInfo.getDeviceType()); - transportService.registerAsyncSession(sessionInfo, new LwM2MSessionMsgListener(this, sessionInfo)); - transportService.process(sessionInfo, DefaultTransportService.getSessionEventMsg(SessionEvent.OPEN), null); - transportService.process(sessionInfo, TransportProtos.SubscribeToAttributeUpdatesMsg.newBuilder().build(), null); - this.sentLogsToThingsboard(LOG_LW2M_INFO + ": Client registration", registration.getId()); - } else { - log.error("Client: [{}] onRegistered [{}] name [{}] sessionInfo ", registration.getId(), registration.getEndpoint(), sessionInfo); - } - } else { - log.error("Client: [{}] onRegistered [{}] name [{}] lwM2MClient ", registration.getId(), registration.getEndpoint(), lwM2MClient); - } - } + void onDeviceProfileUpdate(TransportProtos.SessionInfoProto sessionInfo, DeviceProfile deviceProfile); - /** - * @param lwServer - LeshanServer - * @param registration - Registration LwM2M Client - */ - public void updatedReg(LeshanServer lwServer, Registration registration) { - SessionInfoProto sessionInfo = this.getValidateSessionInfo(registration.getId()); - if (sessionInfo != null) { - log.info("Client: [{}] updatedReg [{}] name [{}] profile ", registration.getId(), registration.getEndpoint(), sessionInfo.getDeviceType()); - } else { - log.error("Client: [{}] updatedReg [{}] name [{}] sessionInfo ", registration.getId(), registration.getEndpoint(), sessionInfo); - } - } + void onDeviceUpdate(TransportProtos.SessionInfoProto sessionInfo, Device device, Optional deviceProfileOpt); - /** - * @param registration - Registration LwM2M Client - * @param observations - All paths observations before unReg - * !!! Warn: if have not finishing unReg, then this operation will be finished on next Client`s connect - */ - public void unReg(Registration registration, Collection observations) { - this.sentLogsToThingsboard(LOG_LW2M_INFO + ": Client unRegistration", registration.getId()); - this.closeClientSession(registration); - } + void doTrigger(LeshanServer lwServer, Registration registration, String path); - private void closeClientSession(Registration registration) { - SessionInfoProto sessionInfo = this.getValidateSessionInfo(registration.getId()); - if (sessionInfo != null) { - transportService.deregisterSession(sessionInfo); - this.doCloseSession(sessionInfo); - lwM2mInMemorySecurityStore.delRemoveSessionAndListener(registration.getId()); - if (lwM2mInMemorySecurityStore.getProfiles().size() > 0) { - this.syncSessionsAndProfiles(); - } - log.info("Client: [{}] unReg [{}] name [{}] profile ", registration.getId(), registration.getEndpoint(), sessionInfo.getDeviceType()); - } else { - log.error("Client: [{}] unReg [{}] name [{}] sessionInfo ", registration.getId(), registration.getEndpoint(), sessionInfo); - } - } + void doDisconnect(TransportProtos.SessionInfoProto sessionInfo); - public void onSleepingDev(Registration registration) { - log.info("[{}] [{}] Received endpoint Sleeping version event", registration.getId(), registration.getEndpoint()); - //TODO: associate endpointId with device information. - } - - /** - * Those methods are called by the protocol stage thread pool, this means that execution MUST be done in a short delay, - * * if you need to do long time processing use a dedicated thread pool. - * - * @param registration - */ - - public void onAwakeDev(Registration registration) { - log.info("[{}] [{}] Received endpoint Awake version event", registration.getId(), registration.getEndpoint()); - //TODO: associate endpointId with device information. - } - - /** - * This method is used to sync with sessions - * Removes a profile if not used in sessions - */ - private void syncSessionsAndProfiles() { - Map profilesClone = lwM2mInMemorySecurityStore.getProfiles().entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - profilesClone.forEach((k, v) -> { - String registrationId = lwM2mInMemorySecurityStore.getSessions().entrySet() - .stream() - .filter(e -> e.getValue().getProfileUuid().equals(k)) - .findFirst() - .map(Map.Entry::getKey) // return the key of the matching entry if found - .orElse(""); - if (registrationId.isEmpty()) { - lwM2mInMemorySecurityStore.getProfiles().remove(k); - } - }); - } - - /** - * Create new LwM2MClient for current session -> setModelClient... - * #1 Add all ObjectLinks (instance) to control the process of executing requests to the client - * to get the client model with current values - * #2 Get the client model with current values. Analyze the response in -> lwM2MTransportRequest.sendResponse - * - * @param lwServer - LeshanServer - * @param registration - Registration LwM2M Client - * @param lwM2MClient - object with All parameters off client - */ - private void setLwM2MClient(LeshanServer lwServer, Registration registration, LwM2MClient lwM2MClient) { - // #1 - Arrays.stream(registration.getObjectLinks()).forEach(url -> { - ResultIds pathIds = new ResultIds(url.getUrl()); - if (pathIds.instanceId > -1 && pathIds.resourceId == -1) { - lwM2MClient.getPendingRequests().add(url.getUrl()); - } - }); - // #2 - Arrays.stream(registration.getObjectLinks()).forEach(url -> { - ResultIds pathIds = new ResultIds(url.getUrl()); - if (pathIds.instanceId > -1 && pathIds.resourceId == -1) { - lwM2MTransportRequest.sendAllRequest(lwServer, registration, url.getUrl(), GET_TYPE_OPER_READ, - ContentFormat.TLV.getName(), lwM2MClient, null, null, this.context.getCtxServer().getTimeout()); - } - }); - } - - /** - * @param registrationId - Id of Registration LwM2M Client - * @return - sessionInfo after access connect client - */ - private SessionInfoProto getValidateSessionInfo(String registrationId) { - SessionInfoProto sessionInfo = null; - LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getlwM2MClient(registrationId); - if (lwM2MClient != null) { - ValidateDeviceCredentialsResponseMsg msg = lwM2MClient.getCredentialsResponse(); - if (msg == null || msg.getDeviceInfo() == null) { - log.error("[{}] [{}]", lwM2MClient.getEndPoint(), CLIENT_NOT_AUTHORIZED); - this.closeClientSession(lwM2MClient.getRegistration()); - } else { - sessionInfo = SessionInfoProto.newBuilder() - .setNodeId(this.context.getNodeId()) - .setSessionIdMSB(lwM2MClient.getSessionUuid().getMostSignificantBits()) - .setSessionIdLSB(lwM2MClient.getSessionUuid().getLeastSignificantBits()) - .setDeviceIdMSB(msg.getDeviceInfo().getDeviceIdMSB()) - .setDeviceIdLSB(msg.getDeviceInfo().getDeviceIdLSB()) - .setTenantIdMSB(msg.getDeviceInfo().getTenantIdMSB()) - .setTenantIdLSB(msg.getDeviceInfo().getTenantIdLSB()) - .setDeviceName(msg.getDeviceInfo().getDeviceName()) - .setDeviceType(msg.getDeviceInfo().getDeviceType()) - .setDeviceProfileIdLSB(msg.getDeviceInfo().getDeviceProfileIdLSB()) - .setDeviceProfileIdMSB(msg.getDeviceInfo().getDeviceProfileIdMSB()) - .build(); - } - } - return sessionInfo; - } - - /** - * Add attribute/telemetry information from Client and credentials/Profile to client model and start observe - * !!! if the resource has an observation, but no telemetry or attribute - the observation will not use - * #1 Client`s starting info to send to thingsboard - * #2 Sending Attribute Telemetry with value to thingsboard only once at the start of the connection - * #3 Start observe - * - * @param lwServer - LeshanServer - * @param registration - Registration LwM2M Client - */ - - public void updatesAndSentModelParameter(LeshanServer lwServer, Registration registration) { - // #1 -// this.setParametersToModelClient(registration, modelClient, deviceProfile); - // #2 - this.updateAttrTelemetry(registration, true, null); - // #3 - this.onSentObserveToClient(lwServer, registration); - } - - - /** - * Sent Attribute and Telemetry to Thingsboard - * #1 - get AttrName/TelemetryName with value: - * #1.1 from Client - * #1.2 from LwM2MClient: - * -- resourceId == path from AttrTelemetryObserveValue.postAttributeProfile/postTelemetryProfile/postObserveProfile - * -- AttrName/TelemetryName == resourceName from ModelObject.objectModel, value from ModelObject.instance.resource(resourceId) - * #2 - set Attribute/Telemetry - * - * @param registration - Registration LwM2M Client - */ - private void updateAttrTelemetry(Registration registration, boolean start, Set paths) { - JsonObject attributes = new JsonObject(); - JsonObject telemetrys = new JsonObject(); - if (start) { - // #1.1 - JsonObject attributeClient = this.getAttributeClient(registration); - if (attributeClient != null) { - attributeClient.entrySet().forEach(p -> { - attributes.add(p.getKey(), p.getValue()); - }); - } - } - // #1.2 - CountDownLatch cancelLatch = new CountDownLatch(1); - this.getParametersFromProfile(attributes, telemetrys, registration, paths); - cancelLatch.countDown(); - try { - cancelLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - log.error("[{}] updateAttrTelemetry", e.toString()); - } - if (attributes.getAsJsonObject().entrySet().size() > 0) - this.updateParametersOnThingsboard(attributes, DEVICE_ATTRIBUTES_TOPIC, registration.getId()); - if (telemetrys.getAsJsonObject().entrySet().size() > 0) - this.updateParametersOnThingsboard(telemetrys, DEVICE_TELEMETRY_TOPIC, registration.getId()); - } - - /** - * get AttrName/TelemetryName with value from Client - * - * @param registration - - * @return - JsonObject, format: {name: value}} - */ - private JsonObject getAttributeClient(Registration registration) { - if (registration.getAdditionalRegistrationAttributes().size() > 0) { - JsonObject resNameValues = new JsonObject(); - registration.getAdditionalRegistrationAttributes().entrySet().forEach(entry -> { - resNameValues.addProperty(entry.getKey(), entry.getValue()); - }); - return resNameValues; - } - return null; - } - - /** - * @param attributes - new JsonObject - * @param telemetry - new JsonObject - * @param registration - Registration LwM2M Client - * result: add to JsonObject those resources to which the user is subscribed and they have a value - * if path==null add All resources else only one - * (attributes/telemetry): new {name(Attr/Telemetry):value} - */ - private void getParametersFromProfile(JsonObject attributes, JsonObject telemetry, Registration registration, Set path) { - AttrTelemetryObserveValue attrTelemetryObserveValue = lwM2mInMemorySecurityStore.getProfiles().get(lwM2mInMemorySecurityStore.getSessions().get(registration.getId()).getProfileUuid()); - attrTelemetryObserveValue.getPostAttributeProfile().forEach(p -> { - ResultIds pathIds = new ResultIds(p.getAsString().toString()); - if (pathIds.getResourceId() > -1) { - if (path == null || path.contains(p.getAsString())) { - this.addParameters(pathIds, p.getAsString().toString(), attributes, registration); - } - } - }); - attrTelemetryObserveValue.getPostTelemetryProfile().forEach(p -> { - ResultIds pathIds = new ResultIds(p.getAsString().toString()); - if (pathIds.getResourceId() > -1) { - if (path == null || path.contains(p.getAsString())) { - this.addParameters(pathIds, p.getAsString().toString(), telemetry, registration); - } - } - }); - } - - /** - * @param pathIds - path resource - * @param parameters - JsonObject attributes/telemetry - * @param registration - Registration LwM2M Client - */ - private void addParameters(ResultIds pathIds, String path, JsonObject parameters, Registration registration) { - ModelObject modelObject = lwM2mInMemorySecurityStore.getSessions().get(registration.getId()).getModelObjects().get(pathIds.getObjectId()); - JsonObject names = lwM2mInMemorySecurityStore.getProfiles().get(lwM2mInMemorySecurityStore.getSessions().get(registration.getId()).getProfileUuid()).getPostKeyNameProfile(); - String resName = String.valueOf(names.get(path)); - if (modelObject != null && resName != null && !resName.isEmpty()) { - String resValue = this.getResourceValue(modelObject, pathIds); - if (resValue != null) { - parameters.addProperty(resName, resValue); - } - } - } - - /** - * @param modelObject - ModelObject of Client - * @param pathIds - path resource - * @return - value of Resource or null - */ - private String getResourceValue(ModelObject modelObject, ResultIds pathIds) { - String resValue = null; - if (modelObject.getInstances().get(pathIds.getInstanceId()) != null) { - LwM2mObjectInstance instance = modelObject.getInstances().get(pathIds.getInstanceId()); - if (instance.getResource(pathIds.getResourceId()) != null) { - resValue = instance.getResource(pathIds.getResourceId()).getType() == OPAQUE ? - Hex.encodeHexString((byte[]) instance.getResource(pathIds.getResourceId()).getValue()).toLowerCase() : - (instance.getResource(pathIds.getResourceId()).isMultiInstances()) ? - instance.getResource(pathIds.getResourceId()).getValues().toString() : - instance.getResource(pathIds.getResourceId()).getValue().toString(); - } - } - return resValue; - } - - /** - * Prepare Sent to Thigsboard callback - Attribute or Telemetry - * - * @param msg - JsonArray: [{name: value}] - * @param topicName - Api Attribute or Telemetry - * @param registrationId - Id of Registration LwM2M Client - */ - public void updateParametersOnThingsboard(JsonElement msg, String topicName, String registrationId) { - SessionInfoProto sessionInfo = this.getValidateSessionInfo(registrationId); - if (sessionInfo != null) { - try { - if (topicName.equals(LwM2MTransportHandler.DEVICE_ATTRIBUTES_TOPIC)) { - PostAttributeMsg postAttributeMsg = adaptor.convertToPostAttributes(msg); - TransportServiceCallback call = this.getPubAckCallbackSentAttrTelemetry(-1, postAttributeMsg); - transportService.process(sessionInfo, postAttributeMsg, call); - } else if (topicName.equals(LwM2MTransportHandler.DEVICE_TELEMETRY_TOPIC)) { - PostTelemetryMsg postTelemetryMsg = adaptor.convertToPostTelemetry(msg); - TransportServiceCallback call = this.getPubAckCallbackSentAttrTelemetry(-1, postTelemetryMsg); - transportService.process(sessionInfo, postTelemetryMsg, this.getPubAckCallbackSentAttrTelemetry(-1, call)); - } - } catch (AdaptorException e) { - log.error("[{}] Failed to process publish msg [{}]", topicName, e); - log.info("[{}] Closing current session due to invalid publish", topicName); - } - } else { - log.error("Client: [{}] updateParametersOnThingsboard [{}] sessionInfo ", registrationId, sessionInfo); - } - } - - /** - * Sent to Thingsboard Attribute || Telemetry - * - * @param msgId - always == -1 - * @param msg - JsonObject: [{name: value}] - * @return - dummy - */ - private TransportServiceCallback getPubAckCallbackSentAttrTelemetry(final int msgId, final T msg) { - return new TransportServiceCallback() { - @Override - public void onSuccess(Void dummy) { - log.trace("Success to publish msg: {}, dummy: {}", msg, dummy); - } - - @Override - public void onError(Throwable e) { - log.trace("[{}] Failed to publish msg: {}", msg, e); - } - }; - } - - - /** - * Start observe - * #1 - Analyze: - * #1.1 path in observe == (attribute or telemetry) - * #1.2 recourseValue notNull - * #2 Analyze after sent request (response): - * #2.1 First: lwM2MTransportRequest.sendResponse -> ObservationListener.newObservation - * #2.2 Next: ObservationListener.onResponse * - * - * @param lwServer - LeshanServer - * @param registration - Registration LwM2M Client - */ - private void onSentObserveToClient(LeshanServer lwServer, Registration registration) { - if (lwServer.getObservationService().getObservations(registration).size() > 0) { - this.setCancelObservations(lwServer, registration); - } - UUID profileUUid = lwM2mInMemorySecurityStore.getSessions().get(registration.getId()).getProfileUuid(); - AttrTelemetryObserveValue attrTelemetryObserveValue = lwM2mInMemorySecurityStore.getProfiles().get(profileUUid); - attrTelemetryObserveValue.getPostObserveProfile().forEach(p -> { - // #1.1 - String target = (getValidateObserve(attrTelemetryObserveValue.getPostAttributeProfile(), p.getAsString().toString())) ? - p.getAsString().toString() : (getValidateObserve(attrTelemetryObserveValue.getPostTelemetryProfile(), p.getAsString().toString())) ? - p.getAsString().toString() : null; - if (target != null) { - // #1.2 - ResultIds pathIds = new ResultIds(target); - ModelObject modelObject = lwM2mInMemorySecurityStore.getSessions().get(registration.getId()).getModelObjects().get(pathIds.getObjectId()); - // #2 - if (modelObject != null) { - if (getResourceValue(modelObject, pathIds) != null) { - lwM2MTransportRequest.sendAllRequest(lwServer, registration, target, GET_TYPE_OPER_OBSERVE, - null, null, null, null, this.context.getCtxServer().getTimeout()); - } - } - } - }); - } - - public void setCancelObservations(LeshanServer lwServer, Registration registration) { - if (registration != null) { - Set observations = lwServer.getObservationService().getObservations(registration); - observations.forEach(observation -> { - this.setCancelObservationRecourse(lwServer, registration, observation.getPath().toString()); - }); - } - } - - /** - * lwM2MTransportRequest.sendAllRequest(lwServer, registration, path, POST_TYPE_OPER_OBSERVE_CANCEL, null, null, null, null, context.getTimeout()); - * At server side this will not remove the observation from the observation store, to do it you need to use - * {@code ObservationService#cancelObservation()} - */ - public void setCancelObservationRecourse(LeshanServer lwServer, Registration registration, String path) { - CountDownLatch cancelLatch = new CountDownLatch(1); - lwServer.getObservationService().cancelObservations(registration, path); - cancelLatch.countDown(); - try { - cancelLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - } - } - - /** - * @param parameters - JsonArray postAttributeProfile/postTelemetryProfile - * @param path - recourse from postObserveProfile - * @return rez - true if path observe is in attribute/telemetry - */ - private boolean getValidateObserve(JsonElement parameters, String path) { - AtomicBoolean rez = new AtomicBoolean(false); - if (parameters.isJsonArray()) { - parameters.getAsJsonArray().forEach(p -> { - if (p.getAsString().toString().equals(path)) rez.set(true); - } - ); - } else if (parameters.isJsonObject()) { - rez.set((parameters.getAsJsonObject().entrySet()).stream().map(json -> json.toString()) - .filter(path::equals).findAny().orElse(null) != null); - } - return rez.get(); - } - - /** - * Sending observe value to thingsboard from ObservationListener.onResponse: object, instance, SingleResource or MultipleResource - * - * @param registration - Registration LwM2M Client - * @param path - observe - * @param response - observe - */ - @SneakyThrows - public void onObservationResponse(Registration registration, String path, ReadResponse response) { - if (response.getContent() != null) { - if (response.getContent() instanceof LwM2mObject) { - LwM2mObject content = (LwM2mObject) response.getContent(); - String target = "/" + content.getId(); - } else if (response.getContent() instanceof LwM2mObjectInstance) { - LwM2mObjectInstance content = (LwM2mObjectInstance) response.getContent(); - } else if (response.getContent() instanceof LwM2mSingleResource) { - LwM2mSingleResource content = (LwM2mSingleResource) response.getContent(); - this.onObservationSetResourcesValue(registration, content.getValue(), null, path); - } else if (response.getContent() instanceof LwM2mMultipleResource) { - LwM2mSingleResource content = (LwM2mSingleResource) response.getContent(); - this.onObservationSetResourcesValue(registration, null, content.getValues(), path); - } - } - } - - /** - * Sending observe value of resources to thingsboard - * #1 Return old Resource from ModelObject - * #2 Create new Resource with value from observation - * #3 Create new Resources from old Resources - * #4 Update new Resources (replace old Resource on new Resource) - * #5 Remove old Instance from modelClient - * #6 Create new Instance with new Resources values - * #7 Update modelClient.getModelObjects(idObject) (replace old Instance on new Instance) - * - * @param registration - Registration LwM2M Client - * @param value - LwM2mSingleResource response.getContent() - * @param values - LwM2mSingleResource response.getContent() - * @param path - resource - */ - private void onObservationSetResourcesValue(Registration registration, Object value, Map values, String path) { - ResultIds resultIds = new ResultIds(path); - // #1 - LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getlwM2MClient(registration.getId()); - ModelObject modelObject = lwM2MClient.getModelObjects().get(resultIds.getObjectId()); - Map instancesModelObject = modelObject.getInstances(); - LwM2mObjectInstance instanceOld = (instancesModelObject.get(resultIds.instanceId) != null) ? instancesModelObject.get(resultIds.instanceId) : null; - Map resourcesOld = (instanceOld != null) ? instanceOld.getResources() : null; - LwM2mResource resourceOld = (resourcesOld != null && resourcesOld.get(resultIds.getResourceId()) != null) ? resourcesOld.get(resultIds.getResourceId()) : null; - // #2 - LwM2mResource resourceNew; - if (resourceOld.isMultiInstances()) { - resourceNew = LwM2mMultipleResource.newResource(resultIds.getResourceId(), values, resourceOld.getType()); - } else { - resourceNew = LwM2mSingleResource.newResource(resultIds.getResourceId(), value, resourceOld.getType()); - } - //#3 - Map resourcesNew = new HashMap<>(resourcesOld); - // #4 - resourcesNew.remove(resourceOld); - // #5 - resourcesNew.put(resultIds.getResourceId(), resourceNew); - // #6 - LwM2mObjectInstance instanceNew = new LwM2mObjectInstance(resultIds.instanceId, resourcesNew.values()); - // #7 - CountDownLatch respLatch = new CountDownLatch(1); - lwM2MClient.getModelObjects().get(resultIds.getObjectId()).removeInstance(resultIds.instanceId); - instancesModelObject.put(resultIds.instanceId, instanceNew); - respLatch.countDown(); - try { - respLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); - } catch (InterruptedException ex) { - } - Set paths = new HashSet(); - paths.add(path); - this.updateAttrTelemetry(registration, false, paths); - } - - /** - * @param updateCredentials - Credentials include config only security Client (without config attr/telemetry...) - * config attr/telemetry... in profile - */ - public void onToTransportUpdateCredentials(ToTransportUpdateCredentialsProto updateCredentials) { - log.info("[{}] idList [{}] valueList updateCredentials", updateCredentials.getCredentialsIdList(), updateCredentials.getCredentialsValueList()); - } - - /** - * Update - sent request in change value resources in Client (path to resources from profile by keyName) - * Only fo resources W - * Delete - nothing - * - * @param msg - - * @param sessionInfo - - */ - public void onAttributeUpdate(TransportProtos.AttributeUpdateNotificationMsg msg, SessionInfoProto sessionInfo) { - if (msg.getSharedUpdatedCount() > 0) { - JsonElement el = JsonConverter.toJson(msg); - el.getAsJsonObject().entrySet().forEach(de -> { - String profilePath = lwM2mInMemorySecurityStore.getProfiles().get(new UUID(sessionInfo.getDeviceProfileIdMSB(), sessionInfo.getDeviceProfileIdLSB())) - .getPostKeyNameProfile().getAsJsonObject().entrySet().stream() - .filter(e -> e.getValue().getAsString().equals(de.getKey())).findFirst().map(Map.Entry::getKey) - .orElse(""); - String path = !profilePath.isEmpty() ? profilePath : this.getPathAttributeUpdate(sessionInfo, de.getKey()); - if (path != null) { - ResultIds resultIds = new ResultIds(path); - LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getSession(new UUID(sessionInfo.getSessionIdMSB(), sessionInfo.getSessionIdLSB())).entrySet().iterator().next().getValue(); - ResourceModel.Operations operations = lwM2MClient.getModelObjects().get(resultIds.getObjectId()).getObjectModel().resources.get(resultIds.getResourceId()).operations; - String value = ((JsonPrimitive) de.getValue()).getAsString(); - if (operations.isWritable()) { - lwM2MTransportRequest.sendAllRequest(lwM2MClient.getLwServer(), lwM2MClient.getRegistration(), path, POST_TYPE_OPER_WRITE_REPLACE, - ContentFormat.TLV.getName(), lwM2MClient, null, value, this.context.getCtxServer().getTimeout()); - log.info("[{}] path onAttributeUpdate", path); - } - else { - log.error(LOG_LW2M_ERROR + ": Resource path - [{}] value - [{}] is not Writable and cannot be updated", path, value); - String logMsg = String.format(LOG_LW2M_ERROR + " attributeUpdate: Resource path - %s value - %s is not Writable and cannot be updated", path, value); - this.sentLogsToThingsboard(logMsg, lwM2MClient.getRegistration().getId()); - } - } - }); - } else if (msg.getSharedDeletedCount() > 0) { - log.info("[{}] delete [{}] onAttributeUpdate", msg.getSharedDeletedList(), sessionInfo); - } - } - - private String getPathAttributeUpdate(SessionInfoProto sessionInfo, String keyName) { - try { - LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getSession(new UUID(sessionInfo.getSessionIdMSB(), sessionInfo.getSessionIdLSB())).entrySet().iterator().next().getValue(); - Predicate> predicateRes = res -> keyName.equals(splitCamelCaseString(res.getValue().name)); - Predicate> predicateObj = (obj -> { - return obj.getValue().getObjectModel().resources.entrySet().stream().filter(predicateRes).findFirst().isPresent(); - }); - Stream> objectStream = lwM2MClient.getModelObjects().entrySet().stream().filter(predicateObj); - Predicate> predicateResFinal = (objectStream.count() > 0) ? predicateRes : res -> keyName.equals(res.getValue().name); - Predicate> predicateObjFinal = (obj -> { - return obj.getValue().getObjectModel().resources.entrySet().stream().filter(predicateResFinal).findFirst().isPresent(); - }); - Map.Entry object = lwM2MClient.getModelObjects().entrySet().stream().filter(predicateObjFinal).findFirst().get(); - ModelObject modelObject = object.getValue(); - LwM2mObjectInstance instance = modelObject.getInstances().entrySet().stream().findFirst().get().getValue(); - ResourceModel resource = modelObject.getObjectModel().resources.entrySet().stream().filter(predicateResFinal).findFirst().get().getValue(); - return new LwM2mPath(object.getKey(), instance.getId(), resource.id).toString(); - } catch (NoSuchElementException e) { - log.error("[{}] keyName [{}]", keyName, e.toString()); - return null; - } - } - - public void onAttributeUpdateOk(Registration registration, String path, WriteRequest request) { - ResultIds resultIds = new ResultIds(path); - LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getlwM2MClient(registration.getId()); - LwM2mResource resource = lwM2MClient.getModelObjects().get(resultIds.getObjectId()).getInstances().get(resultIds.getInstanceId()).getResource(resultIds.getResourceId()); - if (resource.isMultiInstances()) { - this.onObservationSetResourcesValue(registration, null, ((LwM2mSingleResource) request.getNode()).getValues(), path); - } else { - this.onObservationSetResourcesValue(registration, ((LwM2mSingleResource) request.getNode()).getValue(), null, path); - } - } - - /** - * @param sessionInfo - - * @param deviceProfile - - */ - public void onDeviceProfileUpdate(TransportProtos.SessionInfoProto sessionInfo, DeviceProfile deviceProfile) { - String registrationId = lwM2mInMemorySecurityStore.getSessions().entrySet() - .stream() - .filter(e -> e.getValue().getDeviceUuid().equals(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB()))) - .findFirst() - .map(Map.Entry::getKey) - .orElse(""); - if (!registrationId.isEmpty()) { - this.onDeviceUpdateChangeProfile(registrationId, deviceProfile); - } - } - - /** - * @param sessionInfo - - * @param device - - * @param deviceProfileOpt - - */ - public void onDeviceUpdate(TransportProtos.SessionInfoProto sessionInfo, Device device, Optional deviceProfileOpt) { - Optional registrationIdOpt = lwM2mInMemorySecurityStore.getSessions().entrySet().stream() - .filter(e -> device.getUuidId().equals(e.getValue().getDeviceUuid())) - .map(Map.Entry::getKey) - .findFirst(); - registrationIdOpt.ifPresent(registrationId -> this.onDeviceUpdateLwM2MClient(registrationId, device, deviceProfileOpt)); - } - - /** - * Update parameters device in LwM2MClient - * If new deviceProfile != old deviceProfile => update deviceProfile - * - * @param registrationId - - * @param device - - */ - private void onDeviceUpdateLwM2MClient(String registrationId, Device device, Optional deviceProfileOpt) { - LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getSessions().get(registrationId); - lwM2MClient.setDeviceName(device.getName()); - if (!lwM2MClient.getProfileUuid().equals(device.getDeviceProfileId().getId())) { - deviceProfileOpt.ifPresent(deviceProfile -> this.onDeviceUpdateChangeProfile(registrationId, deviceProfile)); - } - } - - /** - * #1 Read new, old Value (Attribute, Telemetry, Observe, KeyName) - * #2 Update in lwM2MClient: ...Profile - * #3 Equivalence test: old <> new Value (Attribute, Telemetry, Observe, KeyName) - * #3.1 Attribute isChange (add&del) - * #3.2 Telemetry isChange (add&del) - * #3.3 KeyName isChange (add) - * #4 update - * #4.1 add If #3 isChange, then analyze and update Value in Transport form Client and sent Value ti thingsboard - * #4.2 del - * -- if add attributes includes del telemetry - result del for observe - * #5 - * #5.1 Observe isChange (add&del) - * #5.2 Observe.add - * -- path Attr/Telemetry includes newObserve and does not include oldObserve: sent Request observe to Client - * #5.3 Observe.del - * -- different between newObserve and oldObserve: sent Request cancel observe to client - * - * @param registrationId - - * @param deviceProfile - - */ - public void onDeviceUpdateChangeProfile(String registrationId, DeviceProfile deviceProfile) { - LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getlwM2MClient(registrationId); - AttrTelemetryObserveValue attrTelemetryObserveValueOld = lwM2mInMemorySecurityStore.getProfiles().get(lwM2MClient.getProfileUuid()); - if (lwM2mInMemorySecurityStore.addUpdateProfileParameters(deviceProfile)) { - LeshanServer lwServer = lwM2MClient.getLwServer(); - Registration registration = lwM2mInMemorySecurityStore.getByRegistration(registrationId); - // #1 - JsonArray attributeOld = attrTelemetryObserveValueOld.getPostAttributeProfile(); - Set attributeSetOld = new Gson().fromJson(attributeOld, Set.class); - JsonArray telemetryOld = attrTelemetryObserveValueOld.getPostTelemetryProfile(); - Set telemetrySetOld = new Gson().fromJson(telemetryOld, Set.class); - JsonArray observeOld = attrTelemetryObserveValueOld.getPostObserveProfile(); - JsonObject keyNameOld = attrTelemetryObserveValueOld.getPostKeyNameProfile(); - - AttrTelemetryObserveValue attrTelemetryObserveValueNew = lwM2mInMemorySecurityStore.getProfiles().get(deviceProfile.getUuidId()); - JsonArray attributeNew = attrTelemetryObserveValueNew.getPostAttributeProfile(); - Set attributeSetNew = new Gson().fromJson(attributeNew, Set.class); - JsonArray telemetryNew = attrTelemetryObserveValueNew.getPostTelemetryProfile(); - Set telemetrySetNew = new Gson().fromJson(telemetryNew, Set.class); - JsonArray observeNew = attrTelemetryObserveValueNew.getPostObserveProfile(); - JsonObject keyNameNew = attrTelemetryObserveValueNew.getPostKeyNameProfile(); - // #2 - lwM2MClient.setDeviceProfileName(deviceProfile.getName()); - lwM2MClient.setProfileUuid(deviceProfile.getUuidId()); - - // #3 - ResultsAnalyzerParameters sentAttrToThingsboard = new ResultsAnalyzerParameters(); - // #3.1 - if (!attributeOld.equals(attributeNew)) { - ResultsAnalyzerParameters postAttributeAnalyzer = this.getAnalyzerParameters(new Gson().fromJson(attributeOld, Set.class), attributeSetNew); - sentAttrToThingsboard.getPathPostParametersAdd().addAll(postAttributeAnalyzer.getPathPostParametersAdd()); - sentAttrToThingsboard.getPathPostParametersDel().addAll(postAttributeAnalyzer.getPathPostParametersDel()); - } - // #3.2 - if (!attributeOld.equals(attributeNew)) { - ResultsAnalyzerParameters postTelemetryAnalyzer = this.getAnalyzerParameters(new Gson().fromJson(telemetryOld, Set.class), telemetrySetNew); - sentAttrToThingsboard.getPathPostParametersAdd().addAll(postTelemetryAnalyzer.getPathPostParametersAdd()); - sentAttrToThingsboard.getPathPostParametersDel().addAll(postTelemetryAnalyzer.getPathPostParametersDel()); - } - // #3.3 - if (!keyNameOld.equals(keyNameNew)) { - ResultsAnalyzerParameters keyNameChange = this.getAnalyzerKeyName(new Gson().fromJson(keyNameOld.toString(), ConcurrentHashMap.class), - new Gson().fromJson(keyNameNew.toString(), ConcurrentHashMap.class)); - sentAttrToThingsboard.getPathPostParametersAdd().addAll(keyNameChange.getPathPostParametersAdd()); - } - - // #4.1 add - if (sentAttrToThingsboard.getPathPostParametersAdd().size() > 0) { - // update value in Resources - this.updateResourceValueObserve(lwServer, registration, lwM2MClient, sentAttrToThingsboard.getPathPostParametersAdd(), GET_TYPE_OPER_READ); - // sent attr/telemetry to tingsboard for new path - this.updateAttrTelemetry(registration, false, sentAttrToThingsboard.getPathPostParametersAdd()); - } - // #4.2 del - if (sentAttrToThingsboard.getPathPostParametersDel().size() > 0) { - ResultsAnalyzerParameters sentAttrToThingsboardDel = this.getAnalyzerParameters(sentAttrToThingsboard.getPathPostParametersAdd(), sentAttrToThingsboard.getPathPostParametersDel()); - sentAttrToThingsboard.setPathPostParametersDel(sentAttrToThingsboardDel.getPathPostParametersDel()); - } - - // #5.1 - if (!observeOld.equals(observeNew)) { - Set observeSetOld = new Gson().fromJson(observeOld, Set.class); - Set observeSetNew = new Gson().fromJson(observeNew, Set.class); - //#5.2 add - // path Attr/Telemetry includes newObserve - attributeSetOld.addAll(telemetrySetOld); - ResultsAnalyzerParameters sentObserveToClientOld = this.getAnalyzerParametersIn(attributeSetOld, observeSetOld); // add observe - attributeSetNew.addAll(telemetrySetNew); - ResultsAnalyzerParameters sentObserveToClientNew = this.getAnalyzerParametersIn(attributeSetNew, observeSetNew); // add observe - // does not include oldObserve - ResultsAnalyzerParameters postObserveAnalyzer = this.getAnalyzerParameters(sentObserveToClientOld.getPathPostParametersAdd(), sentObserveToClientNew.getPathPostParametersAdd()); - // sent Request observe to Client - this.updateResourceValueObserve(lwServer, registration, lwM2MClient, postObserveAnalyzer.getPathPostParametersAdd(), GET_TYPE_OPER_OBSERVE); - // 5.3 del - // sent Request cancel observe to Client - this.cancelObserveIsValue(lwServer, registration, postObserveAnalyzer.getPathPostParametersDel()); - } - } - } - - /** - * Compare old list with new list after change AttrTelemetryObserve in config Profile - * - * @param parametersOld - - * @param parametersNew - - * @return ResultsAnalyzerParameters: add && new - */ - private ResultsAnalyzerParameters getAnalyzerParameters(Set parametersOld, Set parametersNew) { - ResultsAnalyzerParameters analyzerParameters = null; - if (!parametersOld.equals(parametersNew)) { - analyzerParameters = new ResultsAnalyzerParameters(); - analyzerParameters.setPathPostParametersAdd(parametersNew - .stream().filter(p -> !parametersOld.contains(p)).collect(Collectors.toSet())); - analyzerParameters.setPathPostParametersDel(parametersOld - .stream().filter(p -> !parametersNew.contains(p)).collect(Collectors.toSet())); - } - return analyzerParameters; - } - - private ResultsAnalyzerParameters getAnalyzerKeyName(ConcurrentMap keyNameOld, ConcurrentMap keyNameNew) { - ResultsAnalyzerParameters analyzerParameters = new ResultsAnalyzerParameters(); - Set paths = keyNameNew.entrySet() - .stream() - .filter(e -> !e.getValue().equals(keyNameOld.get(e.getKey()))) - .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())).keySet(); - analyzerParameters.setPathPostParametersAdd(paths); - return analyzerParameters; - } - - private ResultsAnalyzerParameters getAnalyzerParametersIn(Set parametersObserve, Set parameters) { - ResultsAnalyzerParameters analyzerParameters = new ResultsAnalyzerParameters(); - analyzerParameters.setPathPostParametersAdd(parametersObserve - .stream().filter(p -> parameters.contains(p)).collect(Collectors.toSet())); - return analyzerParameters; - } - - /** - * Update Resource value after change RezAttrTelemetry in config Profile - * sent response Read to Client and add path to pathResAttrTelemetry in LwM2MClient.getAttrTelemetryObserveValue() - * - * @param lwServer - LeshanServer - * @param registration - Registration LwM2M Client - * @param lwM2MClient - object with All parameters off client - * @param targets - path Resources == [ "/2/0/0", "/2/0/1"] - */ - private void updateResourceValueObserve(LeshanServer lwServer, Registration registration, LwM2MClient lwM2MClient, Set targets, String typeOper) { - targets.stream().forEach(target -> { - ResultIds pathIds = new ResultIds(target); - if (pathIds.resourceId >= 0 && lwM2MClient.getModelObjects().get(pathIds.getObjectId()) - .getInstances().get(pathIds.getInstanceId()).getResource(pathIds.getResourceId()).getValue() != null) { - if (GET_TYPE_OPER_READ.equals(typeOper)) { - lwM2MTransportRequest.sendAllRequest(lwServer, registration, target, typeOper, - ContentFormat.TLV.getName(), null, null, null, this.context.getCtxServer().getTimeout()); - } else if (GET_TYPE_OPER_OBSERVE.equals(typeOper)) { - lwM2MTransportRequest.sendAllRequest(lwServer, registration, target, typeOper, - null, null, null, null, this.context.getCtxServer().getTimeout()); - } - } - }); - } - - private void cancelObserveIsValue(LeshanServer lwServer, Registration registration, Set paramAnallyzer) { - LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getlwM2MClient(registration.getId()); - paramAnallyzer.forEach(p -> { - if (this.getResourceValue(lwM2MClient, p) != null) { - this.setCancelObservationRecourse(lwServer, registration, p); - } - } - ); - } - - private ResourceValue getResourceValue(LwM2MClient lwM2MClient, String path) { - ResourceValue resourceValue = null; - ResultIds pathIds = new ResultIds(path); - if (pathIds.getResourceId() > -1) { - LwM2mResource resource = lwM2MClient.getModelObjects().get(pathIds.getObjectId()).getInstances().get(pathIds.getInstanceId()).getResource(pathIds.getResourceId()); - if (resource.isMultiInstances()) { - Map values = resource.getValues(); - if (resource.getValues().size() > 0) { - resourceValue = new ResourceValue(); - resourceValue.setMultiInstances(resource.isMultiInstances()); - resourceValue.setValues(resource.getValues()); - } - } else { - if (resource.getValue() != null) { - resourceValue = new ResourceValue(); - resourceValue.setMultiInstances(resource.isMultiInstances()); - resourceValue.setValue(resource.getValue()); - } - } - } - return resourceValue; - } - - /** - * Trigger Server path = "/1/0/8" - * - * Trigger bootStrap path = "/1/0/9" - have to implemented on client - */ - public void doTrigger(LeshanServer lwServer, Registration registration, String path) { - lwM2MTransportRequest.sendAllRequest(lwServer, registration, path, POST_TYPE_OPER_EXECUTE, - ContentFormat.TLV.getName(), null, null, null, this.context.getCtxServer().getTimeout()); - } - - /** - * Session device in thingsboard is closed - * - * @param sessionInfo - lwm2m client - */ - private void doCloseSession(SessionInfoProto sessionInfo) { - TransportProtos.SessionEvent event = SessionEvent.CLOSED; - TransportProtos.SessionEventMsg msg = TransportProtos.SessionEventMsg.newBuilder() - .setSessionType(TransportProtos.SessionType.ASYNC) - .setEvent(event).build(); - transportService.process(sessionInfo, msg, null); - } - - /** - * Deregister session in transport - * @param sessionInfo - lwm2m client - */ - private void doDisconnect(SessionInfoProto sessionInfo) { - transportService.process(sessionInfo, DefaultTransportService.getSessionEventMsg(SessionEvent.CLOSED), null); - transportService.deregisterSession(sessionInfo); - } - - private void checkInactivityAndReportActivity() { - lwM2mInMemorySecurityStore.getSessions().forEach((key, value) -> transportService.reportActivity(this.getValidateSessionInfo(key))); - } - - public void sentLogsToThingsboard(String msg, String registrationId) { - if (msg != null) { - JsonObject telemetrys = new JsonObject(); - telemetrys.addProperty(LOG_LW2M_TELEMETRY, msg); - this.updateParametersOnThingsboard(telemetrys, LwM2MTransportHandler.DEVICE_TELEMETRY_TOPIC, registrationId); - } - } } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServiceImpl.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServiceImpl.java new file mode 100644 index 0000000000..10df996b79 --- /dev/null +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServiceImpl.java @@ -0,0 +1,1159 @@ +/** + * Copyright © 2016-2020 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.transport.lwm2m.server; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.leshan.core.Link; +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.node.LwM2mMultipleResource; +import org.eclipse.leshan.core.node.LwM2mObject; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mSingleResource; +import org.eclipse.leshan.core.observation.Observation; +import org.eclipse.leshan.core.request.ContentFormat; +import org.eclipse.leshan.core.request.WriteRequest; +import org.eclipse.leshan.core.response.ReadResponse; +import org.eclipse.leshan.core.util.NamedThreadFactory; +import org.eclipse.leshan.server.californium.LeshanServer; +import org.eclipse.leshan.server.registration.Registration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.stereotype.Service; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.transport.TransportService; +import org.thingsboard.server.common.transport.adaptor.AdaptorException; +import org.thingsboard.server.common.transport.adaptor.JsonConverter; +import org.thingsboard.server.common.transport.service.DefaultTransportService; +import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.gen.transport.TransportProtos.SessionEvent; +import org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto; +import org.thingsboard.server.gen.transport.TransportProtos.ToTransportUpdateCredentialsProto; +import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceCredentialsResponseMsg; +import org.thingsboard.server.transport.lwm2m.server.client.AttrTelemetryObserveValue; +import org.thingsboard.server.transport.lwm2m.server.client.LwM2MClient; +import org.thingsboard.server.transport.lwm2m.server.client.ResourceValue; +import org.thingsboard.server.transport.lwm2m.server.client.ResultsAnalyzerParameters; +import org.thingsboard.server.transport.lwm2m.server.secure.LwM2mInMemorySecurityStore; +import org.thingsboard.server.transport.lwm2m.utils.LwM2mValueConverterImpl; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Random; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.stream.Collectors; + +import static org.thingsboard.server.common.transport.util.JsonUtils.getJsonObject; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.CLIENT_NOT_AUTHORIZED; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.DEVICE_ATTRIBUTES_REQUEST; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.DEVICE_ATTRIBUTES_TOPIC; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.DEVICE_TELEMETRY_TOPIC; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.GET_TYPE_OPER_OBSERVE; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.GET_TYPE_OPER_READ; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LOG_LW2M_ERROR; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LOG_LW2M_INFO; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.LOG_LW2M_TELEMETRY; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.POST_TYPE_OPER_EXECUTE; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.POST_TYPE_OPER_WRITE_REPLACE; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.SERVICE_CHANNEL; +import static org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler.getAckCallback; + +@Slf4j +@Service("LwM2MTransportService") +@ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' ) || ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") +public class LwM2MTransportServiceImpl implements LwM2MTransportService { + + private ExecutorService executorRegistered; + private ExecutorService executorUpdateRegistered; + private ExecutorService executorUnRegistered; + private LwM2mValueConverterImpl converter; + protected final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); + protected final Lock writeLock = readWriteLock.writeLock(); + + + @Autowired + private TransportService transportService; + + @Autowired + public LwM2MTransportContextServer context; + + @Autowired + private LwM2MTransportRequest lwM2MTransportRequest; + + @Autowired + LwM2mInMemorySecurityStore lwM2mInMemorySecurityStore; + + @PostConstruct + public void init() { + this.context.getScheduler().scheduleAtFixedRate(this::checkInactivityAndReportActivity, new Random().nextInt((int) context.getCtxServer().getSessionReportTimeout()), context.getCtxServer().getSessionReportTimeout(), TimeUnit.MILLISECONDS); + this.executorRegistered = Executors.newFixedThreadPool(this.context.getCtxServer().getRegisteredPoolSize(), + new NamedThreadFactory(String.format("LwM2M %s channel registered", SERVICE_CHANNEL))); + this.executorUpdateRegistered = Executors.newFixedThreadPool(this.context.getCtxServer().getUpdateRegisteredPoolSize(), + new NamedThreadFactory(String.format("LwM2M %s channel update registered", SERVICE_CHANNEL))); + this.executorUnRegistered = Executors.newFixedThreadPool(this.context.getCtxServer().getUnRegisteredPoolSize(), + new NamedThreadFactory(String.format("LwM2M %s channel un registered", SERVICE_CHANNEL))); + this.converter = LwM2mValueConverterImpl.getInstance(); + } + + /** + * Start registration device + * Create session: Map, LwM2MClient> + * 1. replaceNewRegistration -> (solving the problem of incorrect termination of the previous session with this endpoint) + * 1.1 When we initialize the registration, we register the session by endpoint. + * 1.2 If the server has incomplete requests (canceling the registration of the previous session), + * delete the previous session only by the previous registration.getId + * 1.2 Add Model (Entity) for client (from registration & observe) by registration.getId + * 1.2 Remove from sessions Model by enpPoint + * Next -> Create new LwM2MClient for current session -> setModelClient... + * + * @param lwServer - LeshanServer + * @param registration - Registration LwM2M Client + * @param previousObsersations - may be null + */ + public void onRegistered(LeshanServer lwServer, Registration registration, Collection previousObsersations) { + executorRegistered.submit(() -> { + try { +// log.warn("[{}] [{{}] Client: create after Registration", registration.getEndpoint(), registration.getId()); + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.updateInSessionsLwM2MClient(lwServer, registration); + if (lwM2MClient != null) { + lwM2MClient.setLwM2MTransportServiceImpl(this); + lwM2MClient.setSessionUuid(UUID.randomUUID()); + this.sentLogsToThingsboard(LOG_LW2M_INFO + ": Client Registered", registration); + this.setLwM2mFromClientValue(lwServer, registration, lwM2MClient); + SessionInfoProto sessionInfo = this.getValidateSessionInfo(registration); + if (sessionInfo != null) { + lwM2MClient.setDeviceUuid(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB())); + lwM2MClient.setProfileUuid(new UUID(sessionInfo.getDeviceProfileIdMSB(), sessionInfo.getDeviceProfileIdLSB())); + lwM2MClient.setDeviceName(sessionInfo.getDeviceName()); + lwM2MClient.setDeviceProfileName(sessionInfo.getDeviceType()); + transportService.registerAsyncSession(sessionInfo, new LwM2MSessionMsgListener(this, sessionInfo)); + transportService.process(sessionInfo, DefaultTransportService.getSessionEventMsg(SessionEvent.OPEN), null); + transportService.process(sessionInfo, TransportProtos.SubscribeToAttributeUpdatesMsg.newBuilder().build(), null); + this.sentLogsToThingsboard(LOG_LW2M_INFO + ": Client create after Registration", registration); + this.putDelayedUpdateResourcesThingsboard(lwM2MClient); + } else { + log.error("Client: [{}] onRegistered [{}] name [{}] sessionInfo ", registration.getId(), registration.getEndpoint(), null); + } + } else { + log.error("Client: [{}] onRegistered [{}] name [{}] lwM2MClient ", registration.getId(), registration.getEndpoint(), null); + } + } catch (Throwable t) { + log.error("[{}] endpoint [{}] error Unable registration.", registration.getEndpoint(), t); + } + }); + } + + /** + * if sessionInfo removed from sessions, then new registerAsyncSession + * + * @param lwServer - LeshanServer + * @param registration - Registration LwM2M Client + */ + public void updatedReg(LeshanServer lwServer, Registration registration) { + executorUpdateRegistered.submit(() -> { + try { + SessionInfoProto sessionInfo = this.getValidateSessionInfo(registration); + if (sessionInfo != null) { + this.checkInactivity(sessionInfo); + log.info("Client: [{}] updatedReg [{}] name [{}] profile ", registration.getId(), registration.getEndpoint(), sessionInfo.getDeviceType()); + } else { + log.error("Client: [{}] updatedReg [{}] name [{}] sessionInfo ", registration.getId(), registration.getEndpoint(), null); + } + } catch (Throwable t) { + log.error("[{}] endpoint [{}] error Unable update registration.", registration.getEndpoint(), t); + } + }); + } + + /** + * @param registration - Registration LwM2M Client + * @param observations - All paths observations before unReg + * !!! Warn: if have not finishing unReg, then this operation will be finished on next Client`s connect + */ + public void unReg(LeshanServer lwServer, Registration registration, Collection observations) { + executorUnRegistered.submit(() -> { + try { + this.setCancelObservations(lwServer, registration); + this.sentLogsToThingsboard(LOG_LW2M_INFO + ": Client unRegistration", registration); + this.closeClientSession(registration); + } catch (Throwable t) { + log.error("[{}] endpoint [{}] error Unable un registration.", registration.getEndpoint(), t); + } + }); + } + + private void closeClientSession(Registration registration) { + SessionInfoProto sessionInfo = this.getValidateSessionInfo(registration); + if (sessionInfo != null) { + transportService.deregisterSession(sessionInfo); + this.doCloseSession(sessionInfo); + lwM2mInMemorySecurityStore.delRemoveSessionAndListener(registration.getId()); + if (lwM2mInMemorySecurityStore.getProfiles().size() > 0) { + this.syncSessionsAndProfiles(); + } + log.info("Client close session: [{}] unReg [{}] name [{}] profile ", registration.getId(), registration.getEndpoint(), sessionInfo.getDeviceType()); + } else { + log.error("Client close session: [{}] unReg [{}] name [{}] sessionInfo ", registration.getId(), registration.getEndpoint(), null); + } + } + + public void onSleepingDev(Registration registration) { + log.info("[{}] [{}] Received endpoint Sleeping version event", registration.getId(), registration.getEndpoint()); + //TODO: associate endpointId with device information. + } + + /** + * Those methods are called by the protocol stage thread pool, this means that execution MUST be done in a short delay, + * * if you need to do long time processing use a dedicated thread pool. + * + * @param registration - + */ + protected void onAwakeDev(Registration registration) { + log.info("[{}] [{}] Received endpoint Awake version event", registration.getId(), registration.getEndpoint()); + //TODO: associate endpointId with device information. + } + + /** + * This method is used to sync with sessions + * Removes a profile if not used in sessions + */ + private void syncSessionsAndProfiles() { + Map profilesClone = lwM2mInMemorySecurityStore.getProfiles().entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + profilesClone.forEach((k, v) -> { + String registrationId = lwM2mInMemorySecurityStore.getSessions().entrySet() + .stream() + .filter(e -> e.getValue().getProfileUuid().equals(k)) + .findFirst() + .map(Map.Entry::getKey) // return the key of the matching entry if found + .orElse(""); + if (registrationId.isEmpty()) { + lwM2mInMemorySecurityStore.getProfiles().remove(k); + } + }); + } + + /** + * #0 Add new ObjectModel to context + * Create new LwM2MClient for current session -> setModelClient... + * #1 Add all ObjectLinks (instance) to control the process of executing requests to the client + * to get the client model with current values + * #2 Get the client model with current values. Analyze the response in -> lwM2MTransportRequest.sendResponse + * + * @param lwServer - LeshanServer + * @param registration - Registration LwM2M Client + * @param lwM2MClient - object with All parameters off client + */ + private void setLwM2mFromClientValue(LeshanServer lwServer, Registration registration, LwM2MClient lwM2MClient) { + Arrays.stream(registration.getObjectLinks()).forEach(url -> { + LwM2mPath pathIds = new LwM2mPath(url.getUrl()); + if (pathIds.isObjectInstance() && !pathIds.isResource()) { + // #1 + lwM2MClient.getPendingRequests().add(url.getUrl()); + // #2 + lwM2MTransportRequest.sendAllRequest(lwServer, registration, url.getUrl(), GET_TYPE_OPER_READ, ContentFormat.TLV.getName(), + lwM2MClient, null, null, this.context.getCtxServer().getTimeout(), false); + } + }); + + // #1 + for (Link url : registration.getObjectLinks()) { + LwM2mPath pathIds = new LwM2mPath(url.getUrl()); + if (pathIds.isObjectInstance() && !pathIds.isResource()) { + lwM2MClient.getPendingRequests().add(url.getUrl()); + } + } + // #2 + for (Link url : registration.getObjectLinks()) { + LwM2mPath pathIds = new LwM2mPath(url.getUrl()); + if (pathIds.isObjectInstance() && !pathIds.isResource()) { + lwM2MTransportRequest.sendAllRequest(lwServer, registration, url.getUrl(), GET_TYPE_OPER_READ, ContentFormat.TLV.getName(), + lwM2MClient, null, null, this.context.getCtxServer().getTimeout(), false); + } + } + + // #1 + Arrays.stream(registration.getObjectLinks()).forEach(url -> { + LwM2mPath pathIds = new LwM2mPath(url.getUrl()); + if (pathIds.isObjectInstance() && !pathIds.isResource()) { + lwM2MClient.getPendingRequests().add(url.getUrl()); + } + }); + + // #2 + Arrays.stream(registration.getObjectLinks()).forEach(url -> { + LwM2mPath pathIds = new LwM2mPath(url.getUrl()); + if (pathIds.isObjectInstance() && !pathIds.isResource()) { + lwM2MTransportRequest.sendAllRequest(lwServer, registration, url.getUrl(), GET_TYPE_OPER_READ, ContentFormat.TLV.getName(), + lwM2MClient, null, null, this.context.getCtxServer().getTimeout(), false); + } + }); + } + + /** + * @param registration - Registration LwM2M Client + * @return - sessionInfo after access connect client + */ + private SessionInfoProto getValidateSessionInfo(Registration registration) { + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getLwM2MClientWithReg(registration, null); + return getNewSessionInfoProto(lwM2MClient); + + } + + /** + * @param registrationId - + * @return - + */ + private SessionInfoProto getValidateSessionInfo(String registrationId) { + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getLwM2MClientWithReg(null, registrationId); + return getNewSessionInfoProto(lwM2MClient); + } + + private SessionInfoProto getNewSessionInfoProto(LwM2MClient lwM2MClient) { + if (lwM2MClient != null) { + ValidateDeviceCredentialsResponseMsg msg = lwM2MClient.getCredentialsResponse(); + if (msg == null || msg.getDeviceInfo() == null) { + log.error("[{}] [{}]", lwM2MClient.getEndPoint(), CLIENT_NOT_AUTHORIZED); + this.closeClientSession(lwM2MClient.getRegistration()); + return null; + } else { + return SessionInfoProto.newBuilder() + .setNodeId(this.context.getNodeId()) + .setSessionIdMSB(lwM2MClient.getSessionUuid().getMostSignificantBits()) + .setSessionIdLSB(lwM2MClient.getSessionUuid().getLeastSignificantBits()) + .setDeviceIdMSB(msg.getDeviceInfo().getDeviceIdMSB()) + .setDeviceIdLSB(msg.getDeviceInfo().getDeviceIdLSB()) + .setTenantIdMSB(msg.getDeviceInfo().getTenantIdMSB()) + .setTenantIdLSB(msg.getDeviceInfo().getTenantIdLSB()) + .setDeviceName(msg.getDeviceInfo().getDeviceName()) + .setDeviceType(msg.getDeviceInfo().getDeviceType()) + .setDeviceProfileIdLSB(msg.getDeviceInfo().getDeviceProfileIdLSB()) + .setDeviceProfileIdMSB(msg.getDeviceInfo().getDeviceProfileIdMSB()) + .build(); + } + } + return null; + } + + /** + * Add attribute/telemetry information from Client and credentials/Profile to client model and start observe + * !!! if the resource has an observation, but no telemetry or attribute - the observation will not use + * #1 Sending Attribute Telemetry with value to thingsboard only once at the start of the connection + * #2 Start observe + * + * @param lwM2MClient - LwM2M Client + */ + + public void updatesAndSentModelParameter(LwM2MClient lwM2MClient) { + // #1 + this.updateAttrTelemetry(lwM2MClient.getRegistration(), true, null); + // #2 + this.onSentObserveToClient(lwM2MClient.getLwServer(), lwM2MClient.getRegistration()); + + } + + /** + * If there is a difference in values between the current resource values and the shared attribute values + * when the client connects to the server + * #1 get attributes name from profile include name resources in ModelObject if resource isWritable + * #2.1 #1 size > 0 => send Request getAttributes to thingsboard + * #2.2 #1 size == 0 => continue normal process + * + * @param lwM2MClient - LwM2M Client + */ + public void putDelayedUpdateResourcesThingsboard(LwM2MClient lwM2MClient) { + SessionInfoProto sessionInfo = this.getValidateSessionInfo(lwM2MClient.getRegistration()); + if (sessionInfo != null) { + //#1.1 + #1.2 + List attrSharedNames = this.getNamesAttrFromProfileIsWritable(lwM2MClient); + if (attrSharedNames.size() > 0) { + //#2.1 + try { + TransportProtos.GetAttributeRequestMsg getAttributeMsg = context.getAdaptor().convertToGetAttributes(null, attrSharedNames); + lwM2MClient.getDelayedRequestsId().add(getAttributeMsg.getRequestId()); + transportService.process(sessionInfo, getAttributeMsg, getAckCallback(lwM2MClient, getAttributeMsg.getRequestId(), DEVICE_ATTRIBUTES_REQUEST)); + } catch (AdaptorException e) { + log.warn("Failed to decode get attributes request", e); + } + } + // #2.2 + else { + lwM2MClient.onSuccessOrErrorDelayedRequests(null); + } + } + } + + /** + * Update resource value on client: if there is a difference in values between the current resource values and the shared attribute values + * #1 Get path resource by result attributesResponse + * #1.1 If two names have equal path => last time attribute + * #2.1 if there is a difference in values between the current resource values and the shared attribute values + * => sent to client Request Update of value (new value from shared attribute) + * and LwM2MClient.delayedRequests.add(path) + * #2.1 if there is not a difference in values between the current resource values and the shared attribute values + * + * @param attributesResponse - + * @param sessionInfo - + */ + public void onGetAttributesResponse(TransportProtos.GetAttributeResponseMsg attributesResponse, TransportProtos.SessionInfoProto sessionInfo) { + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getLwM2MClient(sessionInfo); + if (lwM2MClient.getDelayedRequestsId().contains(attributesResponse.getRequestId())) { + attributesResponse.getSharedAttributeListList().forEach(attr -> { + String path = this.getPathAttributeUpdate(sessionInfo, attr.getKv().getKey()); + // #1.1 + if (lwM2MClient.getDelayedRequests().containsKey(path) && attr.getTs() > lwM2MClient.getDelayedRequests().get(path).getTs()) { + lwM2MClient.getDelayedRequests().put(path, attr); + } else { + lwM2MClient.getDelayedRequests().put(path, attr); + } + }); + // #2.1 + lwM2MClient.getDelayedRequests().forEach((k, v) -> { + ArrayList listV = new ArrayList<>(); + listV.add(v.getKv()); + this.putDelayedUpdateResourcesClient(lwM2MClient, this.getResourceValueToString(lwM2MClient, k), getJsonObject(listV).get(v.getKv().getKey()), k); + }); + lwM2MClient.getDelayedRequestsId().remove(attributesResponse.getRequestId()); + if (lwM2MClient.getDelayedRequests().size() == 0) { + lwM2MClient.onSuccessOrErrorDelayedRequests(null); + } + } + } + + private void putDelayedUpdateResourcesClient(LwM2MClient lwM2MClient, Object valueOld, Object valueNew, String path) { + if (valueNew != null && !valueNew.toString().equals(valueOld.toString())) { + lwM2MTransportRequest.sendAllRequest(lwM2MClient.getLwServer(), lwM2MClient.getRegistration(), path, POST_TYPE_OPER_WRITE_REPLACE, + ContentFormat.TLV.getName(), lwM2MClient, null, valueNew, this.context.getCtxServer().getTimeout(), + true); + } + } + + /** + * Get names and keyNames from profile shared!!!! attr resources IsWritable + * + * @param lwM2MClient - + * @return ArrayList keyNames from profile attr resources shared!!!! && IsWritable + */ + private List getNamesAttrFromProfileIsWritable(LwM2MClient lwM2MClient) { + AttrTelemetryObserveValue profile = lwM2mInMemorySecurityStore.getProfile(lwM2MClient.getProfileUuid()); + Set attrSet = new Gson().fromJson(profile.getPostAttributeProfile(), Set.class); + ConcurrentMap keyNamesMap = new Gson().fromJson(profile.getPostKeyNameProfile().toString(), ConcurrentHashMap.class); + + ConcurrentMap keyNamesIsWritable = keyNamesMap.entrySet() + .stream() + .filter(e -> (attrSet.contains(e.getKey()) && context.getCtxServer().getResourceModel(lwM2MClient.getRegistration(), new LwM2mPath(e.getKey())) != null && + context.getCtxServer().getResourceModel(lwM2MClient.getRegistration(), new LwM2mPath(e.getKey())).operations.isWritable())) + .collect(Collectors.toConcurrentMap(Map.Entry::getKey, Map.Entry::getValue)); + + Set namesIsWritable = ConcurrentHashMap.newKeySet(); + namesIsWritable.addAll(new HashSet<>(keyNamesIsWritable.values())); + return new ArrayList<>(namesIsWritable); + } + + + /** + * Sent Attribute and Telemetry to Thingsboard + * #1 - get AttrName/TelemetryName with value: + * #1.1 from Client + * #1.2 from LwM2MClient: + * -- resourceId == path from AttrTelemetryObserveValue.postAttributeProfile/postTelemetryProfile/postObserveProfile + * -- AttrName/TelemetryName == resourceName from ModelObject.objectModel, value from ModelObject.instance.resource(resourceId) + * #2 - set Attribute/Telemetry + * + * @param registration - Registration LwM2M Client + */ + private void updateAttrTelemetry(Registration registration, boolean start, Set paths) { + JsonObject attributes = new JsonObject(); + JsonObject telemetries = new JsonObject(); + if (start) { + // #1.1 + JsonObject attributeClient = this.getAttributeClient(registration); + if (attributeClient != null) { + attributeClient.entrySet().forEach(p -> attributes.add(p.getKey(), p.getValue())); + } + } + // #1.2 + try { + writeLock.lock(); + this.getParametersFromProfile(attributes, telemetries, registration, paths); + } catch (Exception e) { + log.error("UpdateAttrTelemetry", e); + } finally { + writeLock.unlock(); + } + if (attributes.getAsJsonObject().entrySet().size() > 0) + this.updateParametersOnThingsboard(attributes, DEVICE_ATTRIBUTES_TOPIC, registration); + if (telemetries.getAsJsonObject().entrySet().size() > 0) + this.updateParametersOnThingsboard(telemetries, DEVICE_TELEMETRY_TOPIC, registration); + } + + /** + * get AttrName/TelemetryName with value from Client + * + * @param registration - + * @return - JsonObject, format: {name: value}} + */ + private JsonObject getAttributeClient(Registration registration) { + if (registration.getAdditionalRegistrationAttributes().size() > 0) { + JsonObject resNameValues = new JsonObject(); + registration.getAdditionalRegistrationAttributes().forEach(resNameValues::addProperty); + return resNameValues; + } + return null; + } + + /** + * @param attributes - new JsonObject + * @param telemetry - new JsonObject + * @param registration - Registration LwM2M Client + * result: add to JsonObject those resources to which the user is subscribed and they have a value + * if path==null add All resources else only one + * (attributes/telemetry): new {name(Attr/Telemetry):value} + */ + private void getParametersFromProfile(JsonObject attributes, JsonObject telemetry, Registration registration, Set path) { + AttrTelemetryObserveValue attrTelemetryObserveValue = lwM2mInMemorySecurityStore.getProfiles().get(lwM2mInMemorySecurityStore.getSessions().get(registration.getId()).getProfileUuid()); + attrTelemetryObserveValue.getPostAttributeProfile().forEach(p -> { + LwM2mPath pathIds = new LwM2mPath(p.getAsString().toString()); + if (pathIds.isResource()) { + if (path == null || path.contains(p.getAsString())) { + this.addParameters(p.getAsString().toString(), attributes, registration); + } + } + }); + attrTelemetryObserveValue.getPostTelemetryProfile().forEach(p -> { + LwM2mPath pathIds = new LwM2mPath(p.getAsString().toString()); + if (pathIds.isResource()) { + if (path == null || path.contains(p.getAsString())) { + this.addParameters(p.getAsString().toString(), telemetry, registration); + } + } + }); + } + + /** + * @param parameters - JsonObject attributes/telemetry + * @param registration - Registration LwM2M Client + */ + private void addParameters(String path, JsonObject parameters, Registration registration) { + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getSessions().get(registration.getId()); + JsonObject names = lwM2mInMemorySecurityStore.getProfiles().get(lwM2MClient.getProfileUuid()).getPostKeyNameProfile(); + String resName = String.valueOf(names.get(path)); + if (resName != null && !resName.isEmpty()) { + try { + String resValue = this.getResourceValueToString(lwM2MClient, path); + if (resValue != null) { + parameters.addProperty(resName, resValue); + } + } catch (Exception e) { + log.error(e.getStackTrace().toString()); + } + } + } + + /** + * Prepare Sent to Thigsboard callback - Attribute or Telemetry + * + * @param msg - JsonArray: [{name: value}] + * @param topicName - Api Attribute or Telemetry + * @param registration - Id of Registration LwM2M Client + */ + public void updateParametersOnThingsboard(JsonElement msg, String topicName, Registration registration) { + SessionInfoProto sessionInfo = this.getValidateSessionInfo(registration); + if (sessionInfo != null) { + context.sentParametersOnThingsboard(msg, topicName, sessionInfo); + } else { + log.error("Client: [{}] updateParametersOnThingsboard [{}] sessionInfo ", registration, null); + } + } + + /** + * Start observe + * #1 - Analyze: + * #1.1 path in observe == (attribute or telemetry) + * #2 Analyze after sent request (response): + * #2.1 First: lwM2MTransportRequest.sendResponse -> ObservationListener.newObservation + * #2.2 Next: ObservationListener.onResponse * + * + * @param lwServer - LeshanServer + * @param registration - Registration LwM2M Client + */ + private void onSentObserveToClient(LeshanServer lwServer, Registration registration) { + if (lwServer.getObservationService().getObservations(registration).size() > 0) { + this.setCancelObservations(lwServer, registration); + } + UUID profileUUid = lwM2mInMemorySecurityStore.getSessions().get(registration.getId()).getProfileUuid(); + AttrTelemetryObserveValue attrTelemetryObserveValue = lwM2mInMemorySecurityStore.getProfiles().get(profileUUid); + attrTelemetryObserveValue.getPostObserveProfile().forEach(p -> { + // #1.1 + String target = (getValidateObserve(attrTelemetryObserveValue.getPostAttributeProfile(), p.getAsString().toString())) ? + p.getAsString().toString() : (getValidateObserve(attrTelemetryObserveValue.getPostTelemetryProfile(), p.getAsString().toString())) ? + p.getAsString().toString() : null; + if (target != null) { + // #2 + if (this.getResourceValueToString(lwM2mInMemorySecurityStore.getSessions().get(registration.getId()), target) != null) { + lwM2MTransportRequest.sendAllRequest(lwServer, registration, target, GET_TYPE_OPER_OBSERVE, + null, null, null, null, this.context.getCtxServer().getTimeout(), + false); + } + } + }); + } + + public void setCancelObservations(LeshanServer lwServer, Registration registration) { + if (registration != null) { + Set observations = lwServer.getObservationService().getObservations(registration); + observations.forEach(observation -> this.setCancelObservationRecourse(lwServer, registration, observation.getPath().toString())); + } + } + + /** + * lwM2MTransportRequest.sendAllRequest(lwServer, registration, path, POST_TYPE_OPER_OBSERVE_CANCEL, null, null, null, null, context.getTimeout()); + * At server side this will not remove the observation from the observation store, to do it you need to use + * {@code ObservationService#cancelObservation()} + */ + public void setCancelObservationRecourse(LeshanServer lwServer, Registration registration, String path) { + lwServer.getObservationService().cancelObservations(registration, path); + } + + /** + * @param parameters - JsonArray postAttributeProfile/postTelemetryProfile + * @param path - recourse from postObserveProfile + * @return rez - true if path observe is in attribute/telemetry + */ + private boolean getValidateObserve(JsonElement parameters, String path) { + AtomicBoolean rez = new AtomicBoolean(false); + if (parameters.isJsonArray()) { + parameters.getAsJsonArray().forEach(p -> { + if (p.getAsString().toString().equals(path)) rez.set(true); + } + ); + } else if (parameters.isJsonObject()) { + rez.set((parameters.getAsJsonObject().entrySet()).stream().map(json -> json.toString()) + .filter(path::equals).findAny().orElse(null) != null); + } + return rez.get(); + } + + /** + * Sending observe value to thingsboard from ObservationListener.onResponse: object, instance, SingleResource or MultipleResource + * + * @param registration - Registration LwM2M Client + * @param path - observe + * @param response - observe + */ + + public void onObservationResponse(Registration registration, String path, ReadResponse response) { + if (response.getContent() != null) { + if (response.getContent() instanceof LwM2mObject) { +// LwM2mObject content = (LwM2mObject) response.getContent(); + } else if (response.getContent() instanceof LwM2mObjectInstance) { +// LwM2mObjectInstance content = (LwM2mObjectInstance) response.getContent(); + } else if (response.getContent() instanceof LwM2mSingleResource) { + LwM2mSingleResource content = (LwM2mSingleResource) response.getContent(); + this.onObservationSetResourcesValue(registration, content.getValue(), null, path); + } else if (response.getContent() instanceof LwM2mMultipleResource) { + LwM2mMultipleResource content = (LwM2mMultipleResource) response.getContent(); + this.onObservationSetResourcesValue(registration, null, content.getValues(), path); + } + } + } + + /** + * Sending observe value of resources to thingsboard + * #1 Return old Value Resource from LwM2MClient + * #2 Update new Resources (replace old Resource Value on new Resource Value) + * + * @param registration - Registration LwM2M Client + * @param value - LwM2mSingleResource response.getContent() + * @param values - LwM2mSingleResource response.getContent() + * @param path - resource + */ + private void onObservationSetResourcesValue(Registration registration, Object value, Map values, String path) { + boolean isChange = false; + try { + writeLock.lock(); + // #1 + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getLwM2MClientWithReg(registration, null); + LwM2mPath pathIds = new LwM2mPath(path); +// log.warn("#0 nameDevice: [{}] resultIds: [{}] value: [{}], values: [{}] ", lwM2MClient.getDeviceName(), pathIds, value, values); + ResourceModel.Type resModelType = context.getCtxServer().getResourceModelType(registration, pathIds); + ResourceValue resValueOld = lwM2MClient.getResources().get(path); + // #2 + if (resValueOld.isMultiInstances() && !values.toString().equals(resValueOld.getResourceValue().toString())) { + lwM2MClient.getResources().get(path).setValues(values); +// ResourceValue resourceValue = new ResourceValue(values, null, true); +// lwM2MClient.getResources().put(path, resourceValue); + isChange = true; + } else if (!LwM2MTransportHandler.equalsResourceValue(resValueOld.getValue(), value, resModelType, pathIds)) { + lwM2MClient.getResources().get(path).setValue(value); +// ResourceValue resourceValueOld = lwM2MClient.getResources().get(path); +// lwM2MClient.getResources().remove(resourceValueOld); +// ResourceValue resourceValue = new ResourceValue(null, value, false); +// lwM2MClient.getResources().put(path, resourceValue); + log.warn("upDateResize: [{}] [{}] [{}] [{}]", lwM2MClient.getEndPoint(), lwM2MClient.getResources().size(), value, path); + isChange = true; + } + } catch (Exception e) { + log.error("#1_1 Update ResourcesValue after Observation is unsuccessfully path: [{}] value: [{}] [{}]", path, value, e.toString()); + } finally { + writeLock.unlock(); + } + + if (isChange) { + Set paths = new HashSet<>(); + paths.add(path); + this.updateAttrTelemetry(registration, false, paths); + } + } + + /** + * @param updateCredentials - Credentials include config only security Client (without config attr/telemetry...) + * config attr/telemetry... in profile + */ + public void onToTransportUpdateCredentials(ToTransportUpdateCredentialsProto updateCredentials) { + log.info("[{}] idList [{}] valueList updateCredentials", updateCredentials.getCredentialsIdList(), updateCredentials.getCredentialsValueList()); + } + + /** + * Update - sent request in change value resources in Client + * Path to resources from profile equal keyName or from ModelObject equal name + * Only for resources: isWritable && isPresent as attribute in profile -> AttrTelemetryObserveValue (format: CamelCase) + * Delete - nothing * + * + * @param msg - + */ + public void onAttributeUpdate(TransportProtos.AttributeUpdateNotificationMsg msg, TransportProtos.SessionInfoProto sessionInfo) { + if (msg.getSharedUpdatedCount() > 0) { + JsonElement el = JsonConverter.toJson(msg); + el.getAsJsonObject().entrySet().forEach(de -> { + String path = this.getPathAttributeUpdate(sessionInfo, de.getKey()); + String value = de.getValue().getAsString(); + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getSession(new UUID(sessionInfo.getSessionIdMSB(), sessionInfo.getSessionIdLSB())).entrySet().iterator().next().getValue(); + AttrTelemetryObserveValue profile = lwM2mInMemorySecurityStore.getProfile(new UUID(sessionInfo.getDeviceProfileIdMSB(), sessionInfo.getDeviceProfileIdLSB())); + ResourceModel resourceModel = context.getCtxServer().getResourceModel(lwM2MClient.getRegistration(), new LwM2mPath(path)); + if (!path.isEmpty() && (this.validatePathInAttrProfile(profile, path) || this.validatePathInTelemetryProfile(profile, path))) { + if (resourceModel != null && resourceModel.operations.isWritable()) { + lwM2MTransportRequest.sendAllRequest(lwM2MClient.getLwServer(), lwM2MClient.getRegistration(), path, POST_TYPE_OPER_WRITE_REPLACE, + ContentFormat.TLV.getName(), lwM2MClient, null, value, this.context.getCtxServer().getTimeout(), + false); + } else { + log.error("Resource path - [{}] value - [{}] is not Writable and cannot be updated", path, value); + String logMsg = String.format(LOG_LW2M_ERROR + ": attributeUpdate: Resource path - %s value - %s is not Writable and cannot be updated", path, value); + this.sentLogsToThingsboard(logMsg, lwM2MClient.getRegistration()); + } + } else { + log.error("Attribute name - [{}] value - [{}] is not present as attribute in profile and cannot be updated", de.getKey(), value); + String logMsg = String.format(LOG_LW2M_ERROR + ": attributeUpdate: attribute name - %s value - %s is not present as attribute in profile and cannot be updated", de.getKey(), value); + this.sentLogsToThingsboard(logMsg, lwM2MClient.getRegistration()); + } + }); + } else if (msg.getSharedDeletedCount() > 0) { + log.info("[{}] delete [{}] onAttributeUpdate", msg.getSharedDeletedList(), sessionInfo); + } + } + + /** + * Get path to resource from profile equal keyName or from ModelObject equal name + * Only for resource: isWritable && isPresent as attribute in profile -> AttrTelemetryObserveValue (format: CamelCase) + * + * @param sessionInfo - + * @param name - + * @return path if path isPresent in postProfile + */ + private String getPathAttributeUpdate(TransportProtos.SessionInfoProto sessionInfo, String name) { + String profilePath = this.getPathAttributeUpdateProfile(sessionInfo, name); +// return !profilePath.isEmpty() ? profilePath : this.getPathAttributeUpdateModelObject(name); + return !profilePath.isEmpty() ? profilePath : null; + } + + /** + * @param profile - + * @param path - + * @return true if path isPresent in postAttributeProfile + */ + private boolean validatePathInAttrProfile(AttrTelemetryObserveValue profile, String path) { + Set attributesSet = new Gson().fromJson(profile.getPostAttributeProfile(), Set.class); + return attributesSet.stream().filter(p -> p.equals(path)).findFirst().isPresent(); + } + + /** + * @param profile - + * @param path - + * @return true if path isPresent in postAttributeProfile + */ + private boolean validatePathInTelemetryProfile(AttrTelemetryObserveValue profile, String path) { + Set telemetriesSet = new Gson().fromJson(profile.getPostTelemetryProfile(), Set.class); + return telemetriesSet.stream().filter(p -> p.equals(path)).findFirst().isPresent(); + } + + + /** + * Get path to resource from profile equal keyName + * + * @param sessionInfo - + * @param name - + * @return - + */ + private String getPathAttributeUpdateProfile(TransportProtos.SessionInfoProto sessionInfo, String name) { + AttrTelemetryObserveValue profile = lwM2mInMemorySecurityStore.getProfile(new UUID(sessionInfo.getDeviceProfileIdMSB(), sessionInfo.getDeviceProfileIdLSB())); + return profile.getPostKeyNameProfile().getAsJsonObject().entrySet().stream() + .filter(e -> e.getValue().getAsString().equals(name)).findFirst().map(Map.Entry::getKey) + .orElse(""); + } + + /** + * Update resource (attribute) value on thingsboard after update value in client + * + * @param registration - + * @param path - + * @param request - + */ + public void onAttributeUpdateOk(Registration registration, String path, WriteRequest request, boolean isDelayedUpdate) { + ResourceModel resource = context.getCtxServer().getResourceModel(registration, new LwM2mPath(path)); + if (resource.multiple) { + this.onObservationSetResourcesValue(registration, null, ((LwM2mSingleResource) request.getNode()).getValues(), path); + } else { + this.onObservationSetResourcesValue(registration, ((LwM2mSingleResource) request.getNode()).getValue(), null, path); + } + if (isDelayedUpdate) lwM2mInMemorySecurityStore.getLwM2MClientWithReg(registration, null) + .onSuccessOrErrorDelayedRequests(request.getPath().toString()); + } + + /** + * @param sessionInfo - + * @param deviceProfile - + */ + public void onDeviceProfileUpdate(TransportProtos.SessionInfoProto sessionInfo, DeviceProfile deviceProfile) { + Set registrationIds = lwM2mInMemorySecurityStore.getSessions().entrySet() + .stream() + .filter(e -> e.getValue().getProfileUuid().equals(deviceProfile.getUuidId())) + .map(Map.Entry::getKey).sorted().collect(Collectors.toCollection(LinkedHashSet::new)); + if (registrationIds.size() > 0) { + this.onDeviceUpdateChangeProfile(registrationIds, deviceProfile); + } + } + + /** + * @param sessionInfo - + * @param device - + * @param deviceProfileOpt - + */ + public void onDeviceUpdate(TransportProtos.SessionInfoProto sessionInfo, Device device, Optional deviceProfileOpt) { + Optional registrationIdOpt = lwM2mInMemorySecurityStore.getSessions().entrySet().stream() + .filter(e -> device.getUuidId().equals(e.getValue().getDeviceUuid())) + .map(Map.Entry::getKey) + .findFirst(); + registrationIdOpt.ifPresent(registrationId -> this.onDeviceUpdateLwM2MClient(registrationId, device, deviceProfileOpt)); + } + + /** + * Update parameters device in LwM2MClient + * If new deviceProfile != old deviceProfile => update deviceProfile + * + * @param registrationId - + * @param device - + */ + private void onDeviceUpdateLwM2MClient(String registrationId, Device device, Optional deviceProfileOpt) { + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getSessions().get(registrationId); + lwM2MClient.setDeviceName(device.getName()); + if (!lwM2MClient.getProfileUuid().equals(device.getDeviceProfileId().getId())) { + Set registrationIds = new HashSet<>(); + registrationIds.add(registrationId); + deviceProfileOpt.ifPresent(deviceProfile -> this.onDeviceUpdateChangeProfile(registrationIds, deviceProfile)); + } + + lwM2MClient.setProfileUuid(device.getDeviceProfileId().getId()); + } + + /** + * #1 Read new, old Value (Attribute, Telemetry, Observe, KeyName) + * #2 Update in lwM2MClient: ...Profile if changes from update device + * #3 Equivalence test: old <> new Value (Attribute, Telemetry, Observe, KeyName) + * #3.1 Attribute isChange (add&del) + * #3.2 Telemetry isChange (add&del) + * #3.3 KeyName isChange (add) + * #4 update + * #4.1 add If #3 isChange, then analyze and update Value in Transport form Client and sent Value to thingsboard + * #4.2 del + * -- if add attributes includes del telemetry - result del for observe + * #5 + * #5.1 Observe isChange (add&del) + * #5.2 Observe.add + * -- path Attr/Telemetry includes newObserve and does not include oldObserve: sent Request observe to Client + * #5.3 Observe.del + * -- different between newObserve and oldObserve: sent Request cancel observe to client + * + * @param registrationIds - + * @param deviceProfile - + */ + private void onDeviceUpdateChangeProfile(Set registrationIds, DeviceProfile deviceProfile) { + + AttrTelemetryObserveValue attrTelemetryObserveValueOld = lwM2mInMemorySecurityStore.getProfiles().get(deviceProfile.getUuidId()); + if (lwM2mInMemorySecurityStore.addUpdateProfileParameters(deviceProfile)) { + + // #1 + JsonArray attributeOld = attrTelemetryObserveValueOld.getPostAttributeProfile(); + Set attributeSetOld = new Gson().fromJson(attributeOld, Set.class); + JsonArray telemetryOld = attrTelemetryObserveValueOld.getPostTelemetryProfile(); + Set telemetrySetOld = new Gson().fromJson(telemetryOld, Set.class); + JsonArray observeOld = attrTelemetryObserveValueOld.getPostObserveProfile(); + JsonObject keyNameOld = attrTelemetryObserveValueOld.getPostKeyNameProfile(); + + AttrTelemetryObserveValue attrTelemetryObserveValueNew = lwM2mInMemorySecurityStore.getProfiles().get(deviceProfile.getUuidId()); + JsonArray attributeNew = attrTelemetryObserveValueNew.getPostAttributeProfile(); + Set attributeSetNew = new Gson().fromJson(attributeNew, Set.class); + JsonArray telemetryNew = attrTelemetryObserveValueNew.getPostTelemetryProfile(); + Set telemetrySetNew = new Gson().fromJson(telemetryNew, Set.class); + JsonArray observeNew = attrTelemetryObserveValueNew.getPostObserveProfile(); + JsonObject keyNameNew = attrTelemetryObserveValueNew.getPostKeyNameProfile(); + + // #3 + ResultsAnalyzerParameters sentAttrToThingsboard = new ResultsAnalyzerParameters(); + // #3.1 + if (!attributeOld.equals(attributeNew)) { + ResultsAnalyzerParameters postAttributeAnalyzer = this.getAnalyzerParameters(new Gson().fromJson(attributeOld, Set.class), attributeSetNew); + sentAttrToThingsboard.getPathPostParametersAdd().addAll(postAttributeAnalyzer.getPathPostParametersAdd()); + sentAttrToThingsboard.getPathPostParametersDel().addAll(postAttributeAnalyzer.getPathPostParametersDel()); + } + // #3.2 + if (!attributeOld.equals(attributeNew)) { + ResultsAnalyzerParameters postTelemetryAnalyzer = this.getAnalyzerParameters(new Gson().fromJson(telemetryOld, Set.class), telemetrySetNew); + sentAttrToThingsboard.getPathPostParametersAdd().addAll(postTelemetryAnalyzer.getPathPostParametersAdd()); + sentAttrToThingsboard.getPathPostParametersDel().addAll(postTelemetryAnalyzer.getPathPostParametersDel()); + } + // #3.3 + if (!keyNameOld.equals(keyNameNew)) { + ResultsAnalyzerParameters keyNameChange = this.getAnalyzerKeyName(new Gson().fromJson(keyNameOld.toString(), ConcurrentHashMap.class), + new Gson().fromJson(keyNameNew.toString(), ConcurrentHashMap.class)); + sentAttrToThingsboard.getPathPostParametersAdd().addAll(keyNameChange.getPathPostParametersAdd()); + } + + // #4.1 add + if (sentAttrToThingsboard.getPathPostParametersAdd().size() > 0) { + // update value in Resources + registrationIds.forEach(registrationId -> { + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getLwM2MClientWithReg(null, registrationId); + LeshanServer lwServer = lwM2MClient.getLwServer(); + Registration registration = lwM2mInMemorySecurityStore.getByRegistration(registrationId); + log.warn("[{}] # 4.1", registration.getEndpoint()); + this.updateResourceValueObserve(lwServer, registration, sentAttrToThingsboard.getPathPostParametersAdd(), GET_TYPE_OPER_READ); + // sent attr/telemetry to tingsboard for new path + this.updateAttrTelemetry(registration, false, sentAttrToThingsboard.getPathPostParametersAdd()); + }); + } + // #4.2 del + if (sentAttrToThingsboard.getPathPostParametersDel().size() > 0) { + ResultsAnalyzerParameters sentAttrToThingsboardDel = this.getAnalyzerParameters(sentAttrToThingsboard.getPathPostParametersAdd(), sentAttrToThingsboard.getPathPostParametersDel()); + sentAttrToThingsboard.setPathPostParametersDel(sentAttrToThingsboardDel.getPathPostParametersDel()); + } + + // #5.1 + if (!observeOld.equals(observeNew)) { + Set observeSetOld = new Gson().fromJson(observeOld, Set.class); + Set observeSetNew = new Gson().fromJson(observeNew, Set.class); + //#5.2 add + // path Attr/Telemetry includes newObserve + attributeSetOld.addAll(telemetrySetOld); + ResultsAnalyzerParameters sentObserveToClientOld = this.getAnalyzerParametersIn(attributeSetOld, observeSetOld); // add observe + attributeSetNew.addAll(telemetrySetNew); + ResultsAnalyzerParameters sentObserveToClientNew = this.getAnalyzerParametersIn(attributeSetNew, observeSetNew); // add observe + // does not include oldObserve + ResultsAnalyzerParameters postObserveAnalyzer = this.getAnalyzerParameters(sentObserveToClientOld.getPathPostParametersAdd(), sentObserveToClientNew.getPathPostParametersAdd()); + // sent Request observe to Client + registrationIds.forEach(registrationId -> { + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getLwM2MClient(null, registrationId); + LeshanServer lwServer = lwM2MClient.getLwServer(); + Registration registration = lwM2mInMemorySecurityStore.getByRegistration(registrationId); + log.warn("[{}] # 5.1", registration.getEndpoint()); + this.updateResourceValueObserve(lwServer, registration, postObserveAnalyzer.getPathPostParametersAdd(), GET_TYPE_OPER_OBSERVE); + // 5.3 del + // sent Request cancel observe to Client + this.cancelObserveIsValue(lwServer, registration, postObserveAnalyzer.getPathPostParametersDel()); + }); + } + } + } + + /** + * Compare old list with new list after change AttrTelemetryObserve in config Profile + * + * @param parametersOld - + * @param parametersNew - + * @return ResultsAnalyzerParameters: add && new + */ + private ResultsAnalyzerParameters getAnalyzerParameters(Set parametersOld, Set parametersNew) { + ResultsAnalyzerParameters analyzerParameters = null; + if (!parametersOld.equals(parametersNew)) { + analyzerParameters = new ResultsAnalyzerParameters(); + analyzerParameters.setPathPostParametersAdd(parametersNew + .stream().filter(p -> !parametersOld.contains(p)).collect(Collectors.toSet())); + analyzerParameters.setPathPostParametersDel(parametersOld + .stream().filter(p -> !parametersNew.contains(p)).collect(Collectors.toSet())); + } + return analyzerParameters; + } + + private ResultsAnalyzerParameters getAnalyzerKeyName(ConcurrentMap keyNameOld, ConcurrentMap keyNameNew) { + ResultsAnalyzerParameters analyzerParameters = new ResultsAnalyzerParameters(); + Set paths = keyNameNew.entrySet() + .stream() + .filter(e -> !e.getValue().equals(keyNameOld.get(e.getKey()))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)).keySet(); + analyzerParameters.setPathPostParametersAdd(paths); + return analyzerParameters; + } + + private ResultsAnalyzerParameters getAnalyzerParametersIn(Set parametersObserve, Set parameters) { + ResultsAnalyzerParameters analyzerParameters = new ResultsAnalyzerParameters(); + analyzerParameters.setPathPostParametersAdd(parametersObserve + .stream().filter(parameters::contains).collect(Collectors.toSet())); + return analyzerParameters; + } + + /** + * Update Resource value after change RezAttrTelemetry in config Profile + * sent response Read to Client and add path to pathResAttrTelemetry in LwM2MClient.getAttrTelemetryObserveValue() + * + * @param lwServer - LeshanServer + * @param registration - Registration LwM2M Client + * @param targets - path Resources == [ "/2/0/0", "/2/0/1"] + */ + private void updateResourceValueObserve(LeshanServer lwServer, Registration registration, Set targets, String typeOper) { + targets.forEach(target -> { + LwM2mPath pathIds = new LwM2mPath(target); + if (pathIds.isResource()) { + if (GET_TYPE_OPER_READ.equals(typeOper)) { + lwM2MTransportRequest.sendAllRequest(lwServer, registration, target, typeOper, + ContentFormat.TLV.getName(), null, null, null, this.context.getCtxServer().getTimeout(), + false); + } else if (GET_TYPE_OPER_OBSERVE.equals(typeOper)) { + lwM2MTransportRequest.sendAllRequest(lwServer, registration, target, typeOper, + null, null, null, null, this.context.getCtxServer().getTimeout(), + false); + } + } + }); + } + + private void cancelObserveIsValue(LeshanServer lwServer, Registration registration, Set paramAnallyzer) { + LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getLwM2MClientWithReg(registration, null); + paramAnallyzer.forEach(p -> { + if (this.getResourceValue(lwM2MClient, new LwM2mPath(p)) != null) { + this.setCancelObservationRecourse(lwServer, registration, p); + } + } + ); + } + + private ResourceValue getResourceValue(LwM2MClient lwM2MClient, LwM2mPath pathIds) { + ResourceValue resourceValue = null; + if (pathIds.isResource()) { + resourceValue = lwM2MClient.getResources().get(pathIds.toString()); + } + return resourceValue; + } + + /** + * Trigger Server path = "/1/0/8" + * + * Trigger bootStrap path = "/1/0/9" - have to implemented on client + */ + public void doTrigger(LeshanServer lwServer, Registration registration, String path) { + lwM2MTransportRequest.sendAllRequest(lwServer, registration, path, POST_TYPE_OPER_EXECUTE, + ContentFormat.TLV.getName(), null, null, null, this.context.getCtxServer().getTimeout(), + false); + } + + /** + * Session device in thingsboard is closed + * + * @param sessionInfo - lwm2m client + */ + private void doCloseSession(SessionInfoProto sessionInfo) { + TransportProtos.SessionEvent event = SessionEvent.CLOSED; + TransportProtos.SessionEventMsg msg = TransportProtos.SessionEventMsg.newBuilder() + .setSessionType(TransportProtos.SessionType.ASYNC) + .setEvent(event).build(); + transportService.process(sessionInfo, msg, null); + } + + /** + * Deregister session in transport + * + * @param sessionInfo - lwm2m client + */ + public void doDisconnect(SessionInfoProto sessionInfo) { + transportService.process(sessionInfo, DefaultTransportService.getSessionEventMsg(SessionEvent.CLOSED), null); + transportService.deregisterSession(sessionInfo); + } + + private void checkInactivityAndReportActivity() { + lwM2mInMemorySecurityStore.getSessions().forEach((key, value) -> this.checkInactivity(this.getValidateSessionInfo(key))); + } + + /** + * if sessionInfo removed from sessions, then new registerAsyncSession + * + * @param sessionInfo - + */ + private void checkInactivity(SessionInfoProto sessionInfo) { + if (transportService.reportActivity(sessionInfo) == null) { + transportService.registerAsyncSession(sessionInfo, new LwM2MSessionMsgListener(this, sessionInfo)); + } + } + + public void sentLogsToThingsboard(String msg, Registration registration) { + if (msg != null) { + JsonObject telemetries = new JsonObject(); + telemetries.addProperty(LOG_LW2M_TELEMETRY, msg); + this.updateParametersOnThingsboard(telemetries, LwM2MTransportHandler.DEVICE_TELEMETRY_TOPIC, registration); + } + } + + /** + * @param path - path resource + * @return - value of Resource or null + */ + private String getResourceValueToString(LwM2MClient lwM2MClient, String path) { + LwM2mPath pathIds = new LwM2mPath(path); + ResourceValue resourceValue = this.getResourceValue(lwM2MClient, pathIds); + return (resourceValue == null) ? null : + (String) this.converter.convertValue(resourceValue.getResourceValue(), this.context.getCtxServer().getResourceModelType(lwM2MClient.getRegistration(), pathIds), ResourceModel.Type.STRING, pathIds); + } +} diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2mServerListener.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2mServerListener.java index 4d63da3580..e7f82db0c4 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2mServerListener.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2mServerListener.java @@ -29,10 +29,11 @@ import java.util.Collection; @Slf4j public class LwM2mServerListener { - private LeshanServer lhServer; - private LwM2MTransportService service; - public LwM2mServerListener(LeshanServer lhServer, LwM2MTransportService service) { + private final LeshanServer lhServer; + private final LwM2MTransportServiceImpl service; + + public LwM2mServerListener(LeshanServer lhServer, LwM2MTransportServiceImpl service) { this.lhServer = lhServer; this.service = service; } @@ -43,9 +44,8 @@ public class LwM2mServerListener { */ @Override public void registered(Registration registration, Registration previousReg, - Collection previousObsersations) { - - service.onRegistered(lhServer, registration, previousObsersations); + Collection previousObservations) { + service.onRegistered(lhServer, registration, previousObservations); } /** @@ -63,7 +63,7 @@ public class LwM2mServerListener { @Override public void unregistered(Registration registration, Collection observations, boolean expired, Registration newReg) { - service.unReg(registration, observations); + service.unReg(lhServer, registration, observations); } }; @@ -71,11 +71,13 @@ public class LwM2mServerListener { public final PresenceListener presenceListener = new PresenceListener() { @Override public void onSleeping(Registration registration) { + log.info("onSleeping"); service.onSleepingDev(registration); } @Override public void onAwake(Registration registration) { + log.info("onAwake"); service.onAwakeDev(registration); } }; @@ -92,8 +94,9 @@ public class LwM2mServerListener { if (registration != null) { try { service.onObservationResponse(registration, observation.getPath().toString(), response); - } catch (java.lang.NullPointerException e) { - log.error(e.toString()); + } catch (Exception e) { + log.error("[{}] onResponse", e.toString()); + } } } @@ -108,4 +111,5 @@ public class LwM2mServerListener { log.info("Received newObservation from [{}] endpoint [{}] ", observation.getPath(), registration.getEndpoint()); } }; + } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/ResultIds.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/ResultIds.java deleted file mode 100644 index b5c2f6638e..0000000000 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/ResultIds.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright © 2016-2020 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.lwm2m.server; - -import lombok.Builder; -import lombok.Data; - -@Data -public class ResultIds { - @Builder.Default - int objectId = -1; - @Builder.Default - int instanceId = -1; - @Builder.Default - int resourceId = -1; - - public ResultIds (String path) { - String[] paths = path.split("/"); - if (paths != null && paths.length > 1) { - this.objectId = (paths.length > 1) ? Integer.parseInt(paths[1]) : this.objectId; - this.instanceId = (paths.length > 2) ? Integer.parseInt(paths[2]) : this.instanceId; - this.resourceId = (paths.length > 3) ? Integer.parseInt(paths[3]) : this.resourceId; - } - } -} diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/adaptors/LwM2MJsonAdaptor.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/adaptors/LwM2MJsonAdaptor.java index 47dbe563a2..47c7c01b23 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/adaptors/LwM2MJsonAdaptor.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/adaptors/LwM2MJsonAdaptor.java @@ -24,6 +24,12 @@ import org.thingsboard.server.common.transport.adaptor.AdaptorException; import org.thingsboard.server.common.transport.adaptor.JsonConverter; import org.thingsboard.server.gen.transport.TransportProtos; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; + @Slf4j @Component("LwM2MJsonAdaptor") @ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' )|| ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") @@ -46,4 +52,37 @@ public class LwM2MJsonAdaptor implements LwM2MTransportAdaptor { throw new AdaptorException(ex); } } + + @Override + public TransportProtos.GetAttributeRequestMsg convertToGetAttributes(List clientKeys, List sharedKeys) throws AdaptorException { + return processGetAttributeRequestMsg(clientKeys, sharedKeys); + } + + protected TransportProtos.GetAttributeRequestMsg processGetAttributeRequestMsg(List clientKeys, List sharedKeys) throws AdaptorException { + try { + TransportProtos.GetAttributeRequestMsg.Builder result = TransportProtos.GetAttributeRequestMsg.newBuilder(); + Random random = new Random(); + result.setRequestId(random.nextInt()); + if (clientKeys != null) { + result.addAllClientAttributeNames(clientKeys); + } + if (sharedKeys != null) { + result.addAllSharedAttributeNames(sharedKeys); + } + return result.build(); + } catch (RuntimeException e) { + log.warn("Failed to decode get attributes request", e); + throw new AdaptorException(e); + } + } + + private Set toStringSet(JsonElement requestBody, String name) { + JsonElement element = requestBody.getAsJsonObject().get(name); + if (element != null) { + return new HashSet<>(Arrays.asList(element.getAsString().split(","))); + } else { + return null; + } + } + } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/adaptors/LwM2MTransportAdaptor.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/adaptors/LwM2MTransportAdaptor.java index d4d54f4df8..f1672d2039 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/adaptors/LwM2MTransportAdaptor.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/adaptors/LwM2MTransportAdaptor.java @@ -19,9 +19,13 @@ import com.google.gson.JsonElement; import org.thingsboard.server.common.transport.adaptor.AdaptorException; import org.thingsboard.server.gen.transport.TransportProtos; +import java.util.List; + public interface LwM2MTransportAdaptor { TransportProtos.PostTelemetryMsg convertToPostTelemetry(JsonElement jsonElement) throws AdaptorException; TransportProtos.PostAttributeMsg convertToPostAttributes(JsonElement jsonElement) throws AdaptorException; + + TransportProtos.GetAttributeRequestMsg convertToGetAttributes(List clientKeys, List sharedKeys) throws AdaptorException; } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/LwM2MClient.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/LwM2MClient.java index 3a84a637ac..3c1a886454 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/LwM2MClient.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/LwM2MClient.java @@ -18,20 +18,22 @@ package org.thingsboard.server.transport.lwm2m.server.client; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.eclipse.leshan.core.model.ObjectModel; +import org.eclipse.leshan.core.node.LwM2mMultipleResource; import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; import org.eclipse.leshan.core.response.LwM2mResponse; import org.eclipse.leshan.core.response.ReadResponse; import org.eclipse.leshan.server.californium.LeshanServer; import org.eclipse.leshan.server.registration.Registration; import org.eclipse.leshan.server.security.SecurityInfo; +import org.thingsboard.server.gen.transport.TransportProtos; import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceCredentialsResponseMsg; -import org.thingsboard.server.transport.lwm2m.server.LwM2MTransportService; -import org.thingsboard.server.transport.lwm2m.server.ResultIds; +import org.thingsboard.server.transport.lwm2m.server.LwM2MTransportServiceImpl; +import org.thingsboard.server.transport.lwm2m.utils.LwM2mValueConverterImpl; -import java.util.UUID; import java.util.Map; import java.util.Set; -import java.util.Collection; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @@ -47,36 +49,43 @@ public class LwM2MClient implements Cloneable { private UUID sessionUuid; private UUID profileUuid; private LeshanServer lwServer; - private LwM2MTransportService lwM2MTransportService; + private LwM2MTransportServiceImpl lwM2MTransportServiceImpl; private Registration registration; private ValidateDeviceCredentialsResponseMsg credentialsResponse; private Map attributes; - private Map modelObjects; + private Map resources; private Set pendingRequests; + private Map delayedRequests; + private Set delayedRequestsId; private Map responses; + private final LwM2mValueConverterImpl converter; public Object clone() throws CloneNotSupportedException { return super.clone(); } - public LwM2MClient(String endPoint, String identity, SecurityInfo info, ValidateDeviceCredentialsResponseMsg credentialsResponse, Map attributes, Map modelObjects, UUID profileUuid) { + public LwM2MClient(String endPoint, String identity, SecurityInfo info, ValidateDeviceCredentialsResponseMsg credentialsResponse, UUID profileUuid) { this.endPoint = endPoint; this.identity = identity; this.info = info; this.credentialsResponse = credentialsResponse; - this.attributes = (attributes != null && attributes.size() > 0) ? attributes : new ConcurrentHashMap(); - this.modelObjects = (modelObjects != null && modelObjects.size() > 0) ? modelObjects : new ConcurrentHashMap(); + this.attributes = new ConcurrentHashMap<>(); this.pendingRequests = ConcurrentHashMap.newKeySet(); + this.delayedRequests = new ConcurrentHashMap<>(); + this.resources = new ConcurrentHashMap<>(); + this.delayedRequestsId = ConcurrentHashMap.newKeySet(); this.profileUuid = profileUuid; /** * Key , response instance -> resources: value...> */ this.responses = new ConcurrentHashMap<>(); + this.converter = LwM2mValueConverterImpl.getInstance(); } /** - * Fill with data -> Model client - * @param path - + * Fill with data -> Model client + * + * @param path - * @param response - */ public void onSuccessHandler(String path, LwM2mResponse response) { @@ -84,24 +93,41 @@ public class LwM2MClient implements Cloneable { this.pendingRequests.remove(path); if (this.pendingRequests.size() == 0) { this.initValue(); - this.lwM2MTransportService.updatesAndSentModelParameter(this.lwServer, this.registration); + this.lwM2MTransportServiceImpl.putDelayedUpdateResourcesThingsboard(this); } } private void initValue() { this.responses.forEach((key, resp) -> { - ResultIds pathIds = new ResultIds(key); - if (pathIds.getObjectId() > -1) { - ObjectModel objectModel = ((Collection) this.lwServer.getModelProvider().getObjectModel(registration).getObjectModels()).stream().filter(v -> v.id == pathIds.getObjectId()).collect(Collectors.toList()).get(0); - if (this.modelObjects.get(pathIds.getObjectId()) != null) { - this.modelObjects.get(pathIds.getObjectId()).getInstances().put(((ReadResponse) resp).getContent().getId(), (LwM2mObjectInstance) ((ReadResponse) resp).getContent()); - } else { - Map instances = new ConcurrentHashMap<>(); - instances.put(((ReadResponse) resp).getContent().getId(), (LwM2mObjectInstance) ((ReadResponse) resp).getContent()); - ModelObject modelObject = new ModelObject(objectModel, instances); - this.modelObjects.put(pathIds.getObjectId(), modelObject); + LwM2mPath pathIds = new LwM2mPath(key); + if (pathIds.isObject() || pathIds.isObjectInstance() || pathIds.isResource()) { + ObjectModel objectModel = this.lwServer.getModelProvider().getObjectModel(registration).getObjectModels().stream().filter(v -> v.id == pathIds.getObjectId()).collect(Collectors.toList()).get(0); + if (objectModel != null) { + ((LwM2mObjectInstance)((ReadResponse)resp).getContent()).getResources().forEach((k, v) -> { + String rez = pathIds.toString() + "/" + k; + if (((LwM2mObjectInstance) ((ReadResponse) resp).getContent()).getResource(k) instanceof LwM2mMultipleResource){ + this.resources.put(rez, new ResourceValue(v.getValues(), null, true)); + } + else { + this.resources.put(rez, new ResourceValue(null, v.getValue(), false)); + } + }); } } }); + if (this.responses.size() == 0) this.responses = new ConcurrentHashMap<>(); } + + /** + * if path != null + * @param path + */ + public void onSuccessOrErrorDelayedRequests(String path) { + if (path != null) this.delayedRequests.remove(path); + if (this.delayedRequests.size() == 0 && this.getDelayedRequestsId().size() == 0) { + this.lwM2MTransportServiceImpl.updatesAndSentModelParameter(this); + } + } + } + diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/ModelObject.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/ModelObject.java index 03dcc5013f..fb0ce90e78 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/ModelObject.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/ModelObject.java @@ -21,7 +21,7 @@ import org.eclipse.leshan.core.node.LwM2mObjectInstance; import java.util.Map; @Data -public class ModelObject { +public class ModelObject implements Cloneable { /** * model one on all instance * for each instance only id resource with parameters of resources (observe, attr, telemetry) @@ -38,4 +38,8 @@ public class ModelObject { LwM2mObjectInstance instance = this.instances.get(id); return this.instances.remove(id, instance); } + + public ModelObject clone() throws CloneNotSupportedException { + return (ModelObject) super.clone(); + } } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/ResourceValue.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/ResourceValue.java index 312973b9d0..a4a9d54ada 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/ResourceValue.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/ResourceValue.java @@ -16,11 +16,23 @@ package org.thingsboard.server.transport.lwm2m.server.client; import lombok.Data; + import java.util.Map; @Data public class ResourceValue { - Map values; + Map values; Object value; boolean multiInstances; + + public ResourceValue(Map values, Object value, boolean multiInstances) { + this.values = values; + this.value = value; + this.multiInstances = multiInstances; + } + + public Object getResourceValue() { + return this.multiInstances ? this.values : this.value; + } + } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/secure/LwM2MSetSecurityStoreServer.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/secure/LwM2MSetSecurityStoreServer.java deleted file mode 100644 index 7a37ac4005..0000000000 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/secure/LwM2MSetSecurityStoreServer.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * Copyright © 2016-2020 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.lwm2m.server.secure; - -import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import org.eclipse.leshan.core.util.Hex; -import org.eclipse.leshan.server.californium.LeshanServerBuilder; -import org.eclipse.leshan.server.redis.RedisRegistrationStore; -import org.eclipse.leshan.server.redis.RedisSecurityStore; -import org.eclipse.leshan.server.security.DefaultAuthorizer; -import org.eclipse.leshan.server.security.EditableSecurityStore; -import org.eclipse.leshan.server.security.SecurityChecker; -import org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode; -import org.thingsboard.server.transport.lwm2m.server.LwM2MTransportContextServer; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.util.Pool; - -import java.math.BigInteger; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.KeyStore; -import java.security.PublicKey; -import java.security.PrivateKey; -import java.security.AlgorithmParameters; -import java.security.KeyFactory; -import java.security.GeneralSecurityException; -import java.security.KeyStoreException; -import java.security.cert.X509Certificate; -import java.security.interfaces.ECPublicKey; -import java.security.spec.*; -import java.util.Arrays; - -import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.*; - -@Slf4j -@Data -public class LwM2MSetSecurityStoreServer { - - private KeyStore keyStore; - private X509Certificate certificate; - private PublicKey publicKey; - private PrivateKey privateKey; - private LwM2MTransportContextServer context; - private LwM2mInMemorySecurityStore lwM2mInMemorySecurityStore; - - private LeshanServerBuilder builder; - EditableSecurityStore securityStore; - - public LwM2MSetSecurityStoreServer(LeshanServerBuilder builder, LwM2MTransportContextServer context, LwM2mInMemorySecurityStore lwM2mInMemorySecurityStore, LwM2MSecurityMode dtlsMode) { - this.builder = builder; - this.context = context; - this.lwM2mInMemorySecurityStore = lwM2mInMemorySecurityStore; - /** Set securityStore with new registrationStore */ - switch (dtlsMode) { - /** Use PSK only */ - case PSK: - generatePSK_RPK(); - if (this.privateKey != null && this.privateKey.getEncoded().length > 0) { - builder.setPrivateKey(this.privateKey); - builder.setPublicKey(null); - getParamsPSK(); - } - break; - /** Use RPK only */ - case RPK: - generatePSK_RPK(); - if (this.publicKey != null && this.publicKey.getEncoded().length > 0 && - this.privateKey != null && this.privateKey.getEncoded().length > 0) { - builder.setPublicKey(this.publicKey); - builder.setPrivateKey(this.privateKey); - getParamsRPK(); - } - break; - /** Use x509 only */ - case X509: - setServerWithX509Cert(); - break; - /** No security */ - case NO_SEC: - builder.setTrustedCertificates(new X509Certificate[0]); - break; - /** Use x509 with EST */ - case X509_EST: - // TODO support sentinel pool and make pool configurable - break; - case REDIS: - /** - * Set securityStore with new registrationStore (if use redis store) - * Connect to redis - */ - Pool jedis = null; - try { - jedis = new JedisPool(new URI(this.context.getCtxServer().getRedisUrl())); - securityStore = new RedisSecurityStore(jedis); - builder.setRegistrationStore(new RedisRegistrationStore(jedis)); - } catch (URISyntaxException e) { - e.printStackTrace(); - } - break; - default: - } - - /** Set securityStore with new registrationStore (if not redis)*/ - if (dtlsMode.code < REDIS.code) { - securityStore = lwM2mInMemorySecurityStore; - if (dtlsMode == X509) { - builder.setAuthorizer(new DefaultAuthorizer(securityStore, new SecurityChecker() { - @Override - protected boolean matchX509Identity(String endpoint, String receivedX509CommonName, - String expectedX509CommonName) { - return endpoint.startsWith(expectedX509CommonName); - } - })); - } - } - - /** Set securityStore with new registrationStore */ - builder.setSecurityStore(securityStore); - } - - private void generatePSK_RPK() { - try { - /** Get Elliptic Curve Parameter spec for secp256r1 */ - AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC"); - algoParameters.init(new ECGenParameterSpec("secp256r1")); - ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class); - if (this.context.getCtxServer().getServerPublicX() != null && !this.context.getCtxServer().getServerPublicX().isEmpty() && this.context.getCtxServer().getServerPublicY() != null && !this.context.getCtxServer().getServerPublicY().isEmpty()) { - /** Get point values */ - byte[] publicX = Hex.decodeHex(this.context.getCtxServer().getServerPublicX().toCharArray()); - byte[] publicY = Hex.decodeHex(this.context.getCtxServer().getServerPublicY().toCharArray()); - /** Create key specs */ - KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), - parameterSpec); - /** Get keys */ - this.publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec); - } - if (this.context.getCtxServer().getServerPrivateS() != null && !this.context.getCtxServer().getServerPrivateS().isEmpty()) { - /** Get point values */ - byte[] privateS = Hex.decodeHex(this.context.getCtxServer().getServerPrivateS().toCharArray()); - /** Create key specs */ - KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec); - /** Get keys */ - this.privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec); - } - } catch (GeneralSecurityException | IllegalArgumentException e) { - log.error("[{}] Failed generate Server PSK/RPK", e.getMessage()); - throw new RuntimeException(e); - } - } - - private void setServerWithX509Cert() { - try { - if (this.context.getCtxServer().getKeyStoreValue() != null) { - setBuilderX509(); - X509Certificate rootCAX509Cert = (X509Certificate) this.context.getCtxServer().getKeyStoreValue().getCertificate(this.context.getCtxServer().getRootAlias()); - if (rootCAX509Cert != null) { - X509Certificate[] trustedCertificates = new X509Certificate[1]; - trustedCertificates[0] = rootCAX509Cert; - builder.setTrustedCertificates(trustedCertificates); - } else { - /** by default trust all */ - builder.setTrustedCertificates(new X509Certificate[0]); - } - } - else { - /** by default trust all */ - this.builder.setTrustedCertificates(new X509Certificate[0]); - log.error("Unable to load X509 files for LWM2MServer"); - } - } catch (KeyStoreException ex) { - log.error("[{}] Unable to load X509 files server", ex.getMessage()); - } - } - - private void setBuilderX509() { - /** - * For deb => KeyStorePathFile == yml or commandline: KEY_STORE_PATH_FILE - * For idea => KeyStorePathResource == common/transport/lwm2m/src/main/resources/credentials: in LwM2MTransportContextServer: credentials/serverKeyStore.jks - */ - try { - X509Certificate serverCertificate = (X509Certificate) this.context.getCtxServer().getKeyStoreValue().getCertificate(this.context.getCtxServer().getServerAlias()); - PrivateKey privateKey = (PrivateKey) this.context.getCtxServer().getKeyStoreValue().getKey(this.context.getCtxServer().getServerAlias(), this.context.getCtxServer().getKeyStorePasswordServer() == null ? null : this.context.getCtxServer().getKeyStorePasswordServer().toCharArray()); - this.builder.setPrivateKey(privateKey); - this.builder.setCertificateChain(new X509Certificate[]{serverCertificate}); - } catch (Exception ex) { - log.error("[{}] Unable to load KeyStore files server", ex.getMessage()); - } - } - - private void getParamsPSK() { - log.info("\nServer uses PSK -> private key : \n security key : [{}] \n serverSecureURI : [{}]", - Hex.encodeHexString(this.privateKey.getEncoded()), - this.context.getCtxServer().getServerSecureHost() + ":" + Integer.toString(this.context.getCtxServer().getServerSecurePort())); - } - - private void getParamsRPK() { - if (this.publicKey instanceof ECPublicKey) { - /** Get x coordinate */ - byte[] x = ((ECPublicKey) this.publicKey).getW().getAffineX().toByteArray(); - if (x[0] == 0) - x = Arrays.copyOfRange(x, 1, x.length); - - /** Get Y coordinate */ - byte[] y = ((ECPublicKey) this.publicKey).getW().getAffineY().toByteArray(); - if (y[0] == 0) - y = Arrays.copyOfRange(y, 1, y.length); - - /** Get Curves params */ - String params = ((ECPublicKey) this.publicKey).getParams().toString(); - log.info( - " \nServer uses RPK : \n Elliptic Curve parameters : [{}] \n Public x coord : [{}] \n Public y coord : [{}] \n Public Key (Hex): [{}] \n Private Key (Hex): [{}]", - params, Hex.encodeHexString(x), Hex.encodeHexString(y), - Hex.encodeHexString(this.publicKey.getEncoded()), - Hex.encodeHexString(this.privateKey.getEncoded())); - } else { - throw new IllegalStateException("Unsupported Public Key Format (only ECPublicKey supported)."); - } - } -} diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/secure/LwM2mInMemorySecurityStore.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/secure/LwM2mInMemorySecurityStore.java index 394e7ee5f1..088962cb71 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/secure/LwM2mInMemorySecurityStore.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/secure/LwM2mInMemorySecurityStore.java @@ -17,6 +17,7 @@ package org.thingsboard.server.transport.lwm2m.server.secure; import com.google.gson.JsonObject; import lombok.extern.slf4j.Slf4j; +import org.eclipse.leshan.core.util.Hex; import org.eclipse.leshan.server.californium.LeshanServer; import org.eclipse.leshan.server.registration.Registration; import org.eclipse.leshan.server.security.InMemorySecurityStore; @@ -24,61 +25,75 @@ import org.eclipse.leshan.server.security.SecurityInfo; import org.eclipse.leshan.server.security.SecurityStoreListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.DeviceProfile; -import org.thingsboard.server.transport.lwm2m.secure.LwM2MGetSecurityInfo; +import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode; +import org.thingsboard.server.transport.lwm2m.secure.LwM2mCredentialsSecurityInfoValidator; import org.thingsboard.server.transport.lwm2m.secure.ReadResultSecurityStore; import org.thingsboard.server.transport.lwm2m.server.LwM2MTransportHandler; import org.thingsboard.server.transport.lwm2m.server.client.AttrTelemetryObserveValue; import org.thingsboard.server.transport.lwm2m.server.client.LwM2MClient; import org.thingsboard.server.transport.lwm2m.utils.TypeServer; -import java.util.Map; -import java.util.UUID; import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Collectors; -import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.*; +import static org.thingsboard.server.transport.lwm2m.secure.LwM2MSecurityMode.NO_SEC; @Slf4j -@Component("LwM2mInMemorySecurityStore") +@Service("LwM2mInMemorySecurityStore") @ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true' )|| ('${service.type:null}'=='monolith' && '${transport.lwm2m.enabled}'=='true')") public class LwM2mInMemorySecurityStore extends InMemorySecurityStore { + private static final boolean INFOS_ARE_COMPROMISED = false; + // lock for the two maps - protected final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); - protected final Lock readLock = readWriteLock.readLock(); - protected final Lock writeLock = readWriteLock.writeLock(); - private final boolean infosAreCompromised = false; - protected Map sessions = new ConcurrentHashMap<>(); - protected Map profiles = new ConcurrentHashMap<>(); + private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); + private final Lock readLock = readWriteLock.readLock(); + private final Lock writeLock = readWriteLock.writeLock(); + private final Map sessions = new ConcurrentHashMap<>(); + private Map profiles = new ConcurrentHashMap<>(); private SecurityStoreListener listener; @Autowired - LwM2MGetSecurityInfo lwM2MGetSecurityInfo; + LwM2mCredentialsSecurityInfoValidator lwM2MCredentialsSecurityInfoValidator; + /** + * Start after DefaultAuthorizer or LwM2mPskStore + * @param endPoint - + * @return SecurityInfo + */ @Override public SecurityInfo getByEndpoint(String endPoint) { readLock.lock(); try { String registrationId = this.getByRegistrationId(endPoint, null); - return (registrationId != null && sessions.size() > 0 && sessions.get(registrationId) != null) ? sessions.get(registrationId).getInfo() : this.add(endPoint); + return (registrationId != null && sessions.size() > 0 && sessions.get(registrationId) != null) ? + sessions.get(registrationId).getInfo() : this.addLwM2MClientToSession(endPoint); } finally { readLock.unlock(); } } + /** + * Start after LwM2mPskStore + * @param identity - + * @return SecurityInfo + */ @Override public SecurityInfo getByIdentity(String identity) { readLock.lock(); try { String integrationId = this.getByRegistrationId(null, identity); - return (integrationId != null) ? sessions.get(integrationId).getInfo() : add(identity); + return (integrationId != null) ? sessions.get(integrationId).getInfo() : this.addLwM2MClientToSession(identity); } finally { readLock.unlock(); } @@ -88,7 +103,7 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore { public Collection getAll() { readLock.lock(); try { - return Collections.unmodifiableCollection(this.sessions.entrySet().stream().map(model -> model.getValue().getInfo()).collect(Collectors.toList())); + return Collections.unmodifiableCollection(this.sessions.values().stream().map(LwM2MClient::getInfo).collect(Collectors.toList())); } finally { readLock.unlock(); } @@ -104,7 +119,7 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore { LwM2MClient lwM2MClient = (sessions.get(registrationId) != null) ? sessions.get(registrationId) : null; if (lwM2MClient != null) { if (listener != null) { - listener.securityInfoRemoved(infosAreCompromised, lwM2MClient.getInfo()); + listener.securityInfoRemoved(INFOS_ARE_COMPROMISED, lwM2MClient.getInfo()); } sessions.remove(registrationId); } @@ -118,22 +133,38 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore { this.listener = listener; } - public LwM2MClient getlwM2MClient(String endPoint, String identity) { + public LwM2MClient getLwM2MClient(String endPoint, String identity) { Map.Entry modelClients = (endPoint != null) ? this.sessions.entrySet().stream().filter(model -> endPoint.equals(model.getValue().getEndPoint())).findAny().orElse(null) : this.sessions.entrySet().stream().filter(model -> identity.equals(model.getValue().getIdentity())).findAny().orElse(null); return (modelClients != null) ? modelClients.getValue() : null; } - public LwM2MClient getlwM2MClient(String registrationId) { - return this.sessions.get(registrationId); + public LwM2MClient getLwM2MClientWithReg(Registration registration, String registrationId) { + return registrationId != null ? + this.sessions.get(registrationId) : + this.sessions.containsKey(registration.getId()) ? + this.sessions.get(registration.getId()) : + this.sessions.get(registration.getEndpoint()); + } + + public LwM2MClient getLwM2MClient(TransportProtos.SessionInfoProto sessionInfo) { + return this.getSession(new UUID(sessionInfo.getSessionIdMSB(), sessionInfo.getSessionIdLSB())).entrySet().iterator().next().getValue(); + } - public LwM2MClient getlwM2MClient(LeshanServer lwServer, Registration registration) { + /** + * Update in sessions (LwM2MClient for key registration_Id) after starting registration LwM2MClient in LwM2MTransportServiceImpl + * Remove from sessions LwM2MClient with key registration_Endpoint + * @param lwServer - + * @param registration - + * @return LwM2MClient after adding it to session + */ + public LwM2MClient updateInSessionsLwM2MClient(LeshanServer lwServer, Registration registration) { writeLock.lock(); try { if (this.sessions.get(registration.getEndpoint()) == null) { - this.add(registration.getEndpoint()); + this.addLwM2MClientToSession(registration.getEndpoint()); } LwM2MClient lwM2MClient = this.sessions.get(registration.getEndpoint()); lwM2MClient.setLwServer(lwServer); @@ -154,35 +185,43 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore { return (registrationIds != null && registrationIds.size() > 0) ? registrationIds.get(0) : null; } - public String getByRegistrationId(String credentialsId) { - List registrationIds = (this.sessions.entrySet().stream().filter(model -> credentialsId.equals(model.getValue().getEndPoint())).map(model -> model.getKey()).collect(Collectors.toList()).size() > 0) ? - this.sessions.entrySet().stream().filter(model -> credentialsId.equals(model.getValue().getEndPoint())).map(model -> model.getKey()).collect(Collectors.toList()) : - this.sessions.entrySet().stream().filter(model -> credentialsId.equals(model.getValue().getIdentity())).map(model -> model.getKey()).collect(Collectors.toList()); - return (registrationIds != null && registrationIds.size() > 0) ? registrationIds.get(0) : null; - } - public Registration getByRegistration(String registrationId) { return this.sessions.get(registrationId).getRegistration(); } - private SecurityInfo add(String identity) { - ReadResultSecurityStore store = lwM2MGetSecurityInfo.getSecurityInfo(identity, TypeServer.CLIENT); - UUID profileUuid = (addUpdateProfileParameters(store.getDeviceProfile())) ? store.getDeviceProfile().getUuidId() : null; - if (store.getSecurityInfo() != null) { - if (store.getSecurityMode() < DEFAULT_MODE.code) { + /** + * Add new LwM2MClient to session + * @param identity- + * @return SecurityInfo. If error - SecurityInfoError + * and log: + * - FORBIDDEN - if there is no authorization + * - profileUuid - if the device does not have a profile + * - device - if the thingsboard does not have a device with a name equal to the identity + */ + private SecurityInfo addLwM2MClientToSession(String identity) { + ReadResultSecurityStore store = lwM2MCredentialsSecurityInfoValidator.createAndValidateCredentialsSecurityInfo(identity, TypeServer.CLIENT); + if (store.getSecurityMode() < LwM2MSecurityMode.DEFAULT_MODE.code) { + UUID profileUuid = (store.getDeviceProfile() != null && addUpdateProfileParameters(store.getDeviceProfile())) ? store.getDeviceProfile().getUuidId() : null; + if (store.getSecurityInfo() != null && profileUuid != null) { String endpoint = store.getSecurityInfo().getEndpoint(); - sessions.put(endpoint, new LwM2MClient(endpoint, store.getSecurityInfo().getIdentity(), store.getSecurityInfo(), store.getMsg(), null, null, profileUuid)); + sessions.put(endpoint, new LwM2MClient(endpoint, store.getSecurityInfo().getIdentity(), store.getSecurityInfo(), store.getMsg(), profileUuid)); + } else if (store.getSecurityMode() == NO_SEC.code && profileUuid != null) { + sessions.put(identity, new LwM2MClient(identity, null, null, store.getMsg(), profileUuid)); + } else { + log.error("Registration failed: FORBIDDEN/profileUuid/device [{}] , endpointId: [{}]", profileUuid, identity); + /** + * Return Error securityInfo + */ + byte[] preSharedKey = Hex.decodeHex("0A0B".toCharArray()); + SecurityInfo infoError = SecurityInfo.newPreSharedKeyInfo("error", "error_identity", preSharedKey); + return infoError; + } } - } else { - if (store.getSecurityMode() == NO_SEC.code) - sessions.put(identity, new LwM2MClient(identity, null, null, store.getMsg(), null, null, profileUuid)); - else log.error("Registration failed: FORBIDDEN, endpointId: [{}]", identity); - } - return store.getSecurityInfo(); + return store.getSecurityInfo(); } - public Map getSession (UUID sessionUuId){ - return this.sessions.entrySet().stream().filter(e -> e.getValue().getSessionUuid().equals(sessionUuId)).collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); + public Map getSession(UUID sessionUuId) { + return this.sessions.entrySet().stream().filter(e -> e.getValue().getSessionUuid().equals(sessionUuId)).collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); } public Map getSessions() { @@ -193,14 +232,14 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore { return this.profiles; } - public MapsetProfiles(Map profiles) { + public AttrTelemetryObserveValue getProfile(UUID profileUuId) { + return this.profiles.get(profileUuId); + } + + public Map setProfiles(Map profiles) { return this.profiles = profiles; } - /** - * - * @param deviceProfile - */ public boolean addUpdateProfileParameters(DeviceProfile deviceProfile) { JsonObject profilesConfigData = LwM2MTransportHandler.getObserveAttrTelemetryFromThingsboard(deviceProfile); if (profilesConfigData != null) { @@ -208,5 +247,4 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore { } return (profilesConfigData != null); } - } diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/utils/LwM2mValueConverterImpl.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/utils/LwM2mValueConverterImpl.java index d7cae734a2..4a52124af9 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/utils/LwM2mValueConverterImpl.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/utils/LwM2mValueConverterImpl.java @@ -26,11 +26,19 @@ import org.eclipse.leshan.core.util.StringUtils; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.Date; @Slf4j public class LwM2mValueConverterImpl implements LwM2mValueConverter { + private static final LwM2mValueConverterImpl INSTANCE = new LwM2mValueConverterImpl(); + + public static LwM2mValueConverterImpl getInstance() { + return INSTANCE; + } + @Override public Object convertValue(Object value, Type currentType, Type expectedType, LwM2mPath resourcePath) throws CodecException { @@ -120,6 +128,11 @@ public class LwM2mValueConverterImpl implements LwM2mValueConverter { case INTEGER: case FLOAT: return String.valueOf(value); + case TIME: + String DATE_FORMAT = "MMM d, yyyy HH:mm a"; + Long timeValue = ((Date) value).getTime(); + DateFormat formatter = new SimpleDateFormat(DATE_FORMAT); + return formatter.format(new Date(timeValue)); default: break; } diff --git a/common/transport/lwm2m/src/main/resources/credentials/serverKeyStore.jks b/common/transport/lwm2m/src/main/resources/credentials/serverKeyStore.jks index b5b6c9fa3c..9336dd1168 100644 Binary files a/common/transport/lwm2m/src/main/resources/credentials/serverKeyStore.jks and b/common/transport/lwm2m/src/main/resources/credentials/serverKeyStore.jks differ diff --git a/common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_credentials.sh b/common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_credentials.sh index fd07df3feb..6a1ad298ac 100755 --- a/common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_credentials.sh +++ b/common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_credentials.sh @@ -1,4 +1,4 @@ -#!/bin/sh +#!/bin/bash # # Copyright © 2016-2020 The Thingsboard Authors # @@ -15,9 +15,147 @@ # limitations under the License. # +#p) CLIENT_CN=LwX50900000000 +#s) client_start=0 +#f) client_finish=1 +#a) CLIENT_ALIAS=client_alias_00000000 +#b) BOOTSTRAP_ALIAS=bootstrap +#d) SERVER_ALIAS=server +#j) SERVER_STORE=serverKeyStore.jks +#k) CLIENT_STORE=clientKeyStore.jks +#c) CLIENT_STORE_PWD=client_ks_password +#w) SERVER_STORE_PWD=server_ks_password + +#while test $# -gt 0; do +# case "$1" in +# -h|--help) +# echo "$package - attempt to capture frames" +# echo " " +# echo "$package [options] application [arguments]" +# echo " " +# echo "options:" +# echo "-h, --help show brief help" +# echo "-a, --action=ACTION specify an action to use" +# echo "-o, --output-dir=DIR specify a directory to store output in" +# exit 0 +# ;; +# -a) +# shift +# if test $# -gt 0; then +# export PROCESS=$1 +# else +# echo "no process specified" +# exit 1 +# fi +# shift +# ;; +# --action*) +# export PROCESS=`echo $1 | sed -e 's/^[^=]*=//g'` +# shift +# ;; +# -o) +# shift +# if test $# -gt 0; then +# export OUTPUT=$1 +# else +# echo "no output dir specified" +# exit 1 +# fi +# shift +# ;; +# --output-dir*) +# export OUTPUT=`echo $1 | sed -e 's/^[^=]*=//g'` +# shift +# ;; +# *) +# break +# ;; +# esac +#done + + +while getopts p:s:f:a:b:d:j:k:c:w: flag; do + case "${flag}" in + p) client_prefix=${OPTARG} ;; + s) client_start=${OPTARG} ;; + f) client_finish=${OPTARG} ;; + a) client_alias=${OPTARG} ;; + b) bootstrap_alias=${OPTARG} ;; + d) server_alias=${OPTARG} ;; + j) key_store_server_file=${OPTARG} ;; + k) key_store_client_file=${OPTARG} ;; + c) client_key_store_pwd=${OPTARG} ;; + w) server_key_store_pwd=${OPTARG} ;; + esac +done + +# cd to dir of script +script_dir=$(dirname $0) +echo "script_dir: $script_dir" +cd $script_dir # source the properties: . ./lwM2M_keygen.properties + +if [ -n "$client_prefix" ]; then + CLIENT_PREFIX=$client_prefix +fi + +if [ -z "$client_start" ]; then + client_start=0 +fi + +if [ -z "$client_finish" ]; then + client_finish=1 +fi + +if [ -n "$client_alias" ]; then + CLIENT_ALIAS=$client_alias +fi + +if [ -n "$bootstrap_alias" ]; then + BOOTSTRAP_ALIAS=$bootstrap_alias +fi + +if [ -n "$server_alias" ]; then + SERVER_ALIAS=$server_alias +fi + +if [ -n "$key_store_server_file" ]; then + SERVER_STORE=$key_store_server_file +fi + +if [ -n "$key_store_client_file" ]; then + CLIENT_STORE=$key_store_client_file +fi + +if [ -n "$client_key_store_pwd" ]; then + CLIENT_STORE_PWD=$client_key_store_pwd +fi + +if [ -n "$server_key_store_pwd" ]; then + SERVER_STORE_PWD=$server_key_store_pwd +fi + +echo "==Start==" +echo "CLIENT_PREFIX: $CLIENT_PREFIX" +echo "client_start: $client_start" +echo "client_finish: $client_finish" +echo "CLIENT_ALIAS: $CLIENT_ALIAS" +echo "BOOTSTRAP_ALIAS: $BOOTSTRAP_ALIAS" +echo "SERVER_ALIAS: $SERVER_ALIAS" +echo "SERVER_STORE: $SERVER_STORE" +echo "CLIENT_STORE: $CLIENT_STORE" +echo "CLIENT_STORE_PWD: $CLIENT_STORE_PWD" +echo "SERVER_STORE_PWD: $SERVER_STORE_PWD" + +end_point() { + echo "$CLIENT_PREFIX$(printf "%08d" $CLIENT_NUMBER)" +} +client_alias_point() { + echo "$CLIENT_ALIAS$(printf "%08d" $CLIENT_NUMBER)" +} + # Generation of the keystore. echo "${H0}====START========${RESET}" echo "${H1}Server Keystore : ${RESET}" @@ -52,7 +190,7 @@ keytool \ -exportcert \ -alias $SERVER_ALIAS \ -keystore $SERVER_STORE \ - -storepass $SERVER_STORE_PWD | \ + -storepass $SERVER_STORE_PWD | keytool \ -importcert \ -alias $SERVER_SELF_ALIAS \ @@ -67,22 +205,22 @@ keytool \ -alias $SERVER_ALIAS \ -dname "CN=$SERVER_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ -keystore $SERVER_STORE \ - -storepass $SERVER_STORE_PWD | \ + -storepass $SERVER_STORE_PWD | keytool \ -gencert \ -alias $ROOT_KEY_ALIAS \ -keystore $SERVER_STORE \ -storepass $SERVER_STORE_PWD \ -storetype $STORETYPE \ - -validity $VALIDITY | \ - keytool \ - -importcert \ - -alias $SERVER_ALIAS \ - -keystore $SERVER_STORE \ - -storepass $SERVER_STORE_PWD + -validity $VALIDITY | + keytool \ + -importcert \ + -alias $SERVER_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD echo -echo "${H2}Creating server key and self-signed certificate ...${RESET}" +echo "${H2}Creating bootstrap key and self-signed certificate ...${RESET}" keytool \ -genkeypair \ -alias $BOOTSTRAP_ALIAS \ @@ -97,7 +235,7 @@ keytool \ -exportcert \ -alias $BOOTSTRAP_ALIAS \ -keystore $SERVER_STORE \ - -storepass $SERVER_STORE_PWD | \ + -storepass $SERVER_STORE_PWD | keytool \ -importcert \ -alias $BOOTSTRAP_SELF_ALIAS \ @@ -112,54 +250,53 @@ keytool \ -alias $BOOTSTRAP_ALIAS \ -dname "CN=$BOOTSTRAP_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ -keystore $SERVER_STORE \ - -storepass $SERVER_STORE_PWD | \ + -storepass $SERVER_STORE_PWD | keytool \ -gencert \ -alias $ROOT_KEY_ALIAS \ -keystore $SERVER_STORE \ -storepass $SERVER_STORE_PWD \ -storetype $STORETYPE \ - -validity $VALIDITY | \ - keytool \ - -importcert \ - -alias $BOOTSTRAP_ALIAS \ - -keystore $SERVER_STORE \ - -storepass $SERVER_STORE_PWD - + -validity $VALIDITY | + keytool \ + -importcert \ + -alias $BOOTSTRAP_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD echo echo "${H1}Client Keystore : ${RESET}" echo "${H1}==================${RESET}" -echo "${H2}Creating client key and self-signed certificate with expected CN...${RESET}" -keytool \ - -genkeypair \ - -alias $CLIENT_ALIAS \ - -keyalg EC \ - -dname "CN=$CLIENT_SELF_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ - -validity $VALIDITY \ - -storetype $STORETYPE \ - -keypass $CLIENT_STORE_PWD \ - -keystore $CLIENT_STORE \ - -storepass $CLIENT_STORE_PWD -keytool \ - -exportcert \ - -alias $CLIENT_ALIAS \ - -keystore $CLIENT_STORE \ - -storepass $CLIENT_STORE_PWD | \ - keytool \ - -importcert \ - -alias $CLIENT_SELF_ALIAS \ - -keystore $CLIENT_STORE \ - -storepass $CLIENT_STORE_PWD \ - -noprompt +#echo "${H2}Creating client key and self-signed certificate with expected CN...${RESET}" +#keytool \ +# -genkeypair \ +# -alias $CLIENT_ALIAS \ +# -keyalg EC \ +# -dname "CN=$CLIENT_SELF_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ +# -validity $VALIDITY \ +# -storetype $STORETYPE \ +# -keypass $CLIENT_STORE_PWD \ +# -keystore $CLIENT_STORE \ +# -storepass $CLIENT_STORE_PWD +#keytool \ +# -exportcert \ +# -alias $CLIENT_ALIAS \ +# -keystore $CLIENT_STORE \ +# -storepass $CLIENT_STORE_PWD | \ +# keytool \ +# -importcert \ +# -alias $CLIENT_SELF_ALIAS \ +# -keystore $CLIENT_STORE \ +# -storepass $CLIENT_STORE_PWD \ +# -noprompt echo -echo "${H2}Import root certificate just to be able to import ned by root CA with expected CN...${RESET}" +echo "${H2}Import root certificate just to be able to import need by root CA with expected CN...${RESET}" keytool \ -exportcert \ -alias $ROOT_KEY_ALIAS \ -keystore $SERVER_STORE \ - -storepass $SERVER_STORE_PWD | \ + -storepass $SERVER_STORE_PWD | keytool \ -importcert \ -alias $ROOT_KEY_ALIAS \ @@ -167,27 +304,85 @@ keytool \ -storepass $CLIENT_STORE_PWD \ -noprompt -echo -echo "${H2}Creating client certificate signed by root CA with expected CN...${RESET}" -keytool \ - -certreq \ - -alias $CLIENT_ALIAS \ - -dname "CN=$CLIENT_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ - -keystore $CLIENT_STORE \ - -storepass $CLIENT_STORE_PWD | \ +#echo +#echo "${H2}Creating client certificate signed by root CA with expected CN...${RESET}" +#keytool \ +# -certreq \ +# -alias $CLIENT_ALIAS \ +# -dname "CN=$CLIENT_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ +# -keystore $CLIENT_STORE \ +# -storepass $CLIENT_STORE_PWD | \ +# keytool \ +# -gencert \ +# -alias $ROOT_KEY_ALIAS \ +# -keystore $SERVER_STORE \ +# -storepass $SERVER_STORE_PWD \ +# -storetype $STORETYPE \ +# -validity $VALIDITY | \ +# keytool \ +# -importcert \ +# -alias $CLIENT_ALIAS \ +# -keystore $CLIENT_STORE \ +# -storepass $CLIENT_STORE_PWD \ +# -noprompt + +cert_end_point() { + echo "${H2}Creating client key and self-signed certificate with expected CN $CLIENT_SELF_CN ${RESET}" keytool \ - -gencert \ - -alias $ROOT_KEY_ALIAS \ - -keystore $SERVER_STORE \ - -storepass $SERVER_STORE_PWD \ + -genkeypair \ + -alias $CLIENT_CN_ALIAS \ + -keyalg EC \ + -dname "CN=$CLIENT_SELF_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ + -validity $VALIDITY \ -storetype $STORETYPE \ - -validity $VALIDITY | \ + -keypass $CLIENT_STORE_PWD \ + -keystore $CLIENT_STORE \ + -storepass $CLIENT_STORE_PWD + keytool \ + -exportcert \ + -alias $CLIENT_CN_ALIAS \ + -keystore $CLIENT_STORE \ + -storepass $CLIENT_STORE_PWD | + keytool \ + -importcert \ + -alias $CLIENT_SELF_ALIAS \ + -keystore $CLIENT_STORE \ + -storepass $CLIENT_STORE_PWD \ + -noprompt + + echo + echo "${H2}Creating client certificate signed by root CA with expected $CLIENT_CN_NAME ${RESET}" + keytool \ + -certreq \ + -alias $CLIENT_CN_ALIAS \ + -dname "CN=$CLIENT_CN_NAME, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ + -keystore $CLIENT_STORE \ + -storepass $CLIENT_STORE_PWD | + keytool \ + -gencert \ + -alias $ROOT_KEY_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD \ + -storetype $STORETYPE \ + -validity $VALIDITY | keytool \ -importcert \ - -alias $CLIENT_ALIAS \ + -alias $CLIENT_CN_ALIAS \ -keystore $CLIENT_STORE \ -storepass $CLIENT_STORE_PWD \ -noprompt +} + +while [ "$CLIENT_NUMBER" != "$client_finish" ]; do + CLIENT_CN_NAME=$(end_point) + CLIENT_CN_ALIAS=$(client_alias_point) + echo "$CLIENT_CN_NAME" + echo "$CLIENT_CN_ALIAS" + cert_end_point + CLIENT_NUMBER=$(($CLIENT_NUMBER + 1)) + echo "number $CLIENT_NUMBER" + echo "finish $client_finish" +done echo echo "${H0}!!! Warning ${H2}Migrate ${H1}${SERVER_STORE} ${H2}to ${H1}PKCS12 ${H2}which is an industry standard format..${RESET}" diff --git a/common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_keygen.properties b/common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_keygen.properties index 8dd2c30a9a..18f851e4dd 100644 --- a/common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_keygen.properties +++ b/common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_keygen.properties @@ -17,7 +17,7 @@ # Keystore common parameters ROOT_KEY_ALIAS=rootCA DOMAIN_SUFFIX="$(hostname)" -ROOT_CN="$DOMAIN_SUFFIX rootCA" +ROOT_CN="$DOMAIN_SUFFIX $ROOT_KEY_ALIAS" ORGANIZATIONAL_UNIT=Thingsboard ORGANIZATION=Thingsboard CITY=SF @@ -27,23 +27,22 @@ VALIDITY=36500 #days STORETYPE="JKS" #Server -SERVER_STORE=serverKeyStore.jks -SERVER_STORE_PWD=server_ks_password -SERVER_ALIAS=server +SERVER_STORE=serverKeyStore1.jks +SERVER_STORE_PWD=server_ks_password1 +SERVER_ALIAS=server1 SERVER_CN="$DOMAIN_SUFFIX server LwM2M signed by root CA" SERVER_SELF_ALIAS=server_self_signed SERVER_SELF_CN="$DOMAIN_SUFFIX server LwM2M self-signed" -BOOTSTRAP_ALIAS=bootstrap +BOOTSTRAP_ALIAS=bootstrap1 BOOTSTRAP_CN="$DOMAIN_SUFFIX bootstrap server LwM2M signed by root CA" BOOTSTRAP_SELF_ALIAS=bootstrap_self_signed BOOTSTRAP_SELF_CN="$DOMAIN_SUFFIX bootstrap server LwM2M self-signed" # Client -CLIENT_STORE=clientKeyStore.jks -CLIENT_STORE_PWD=client_ks_password -CLIENT_ALIAS=client -#CLIENT_CN=client_lwm2m_x509 -CLIENT_CN=mobile_lwm2m_x509 +CLIENT_STORE=clientKeyStore1.jks +CLIENT_STORE_PWD=client_ks_password1 +CLIENT_ALIAS=client_alias_1 +CLIENT_PREFIX=LwX509_ CLIENT_SELF_ALIAS=client_self_signed CLIENT_SELF_CN="$DOMAIN_SUFFIX client LwM2M self-signed" diff --git a/common/transport/lwm2m/src/main/resources/models/LWM2M_Connectivity_Monitoring-v1_0_2.xml b/common/transport/lwm2m/src/main/resources/models/LWM2M_Connectivity_Monitoring-v1_0_2.xml deleted file mode 100644 index 28957f5a5d..0000000000 --- a/common/transport/lwm2m/src/main/resources/models/LWM2M_Connectivity_Monitoring-v1_0_2.xml +++ /dev/null @@ -1,208 +0,0 @@ - - - - - Connectivity Monitoring - - This LwM2M Object enables monitoring of parameters related to network connectivity. In this general connectivity Object, the Resources are limited to the most general cases common to most network bearers. It is recommended to read the description, which refers to relevant standard development organizations (e.g. 3GPP, IEEE). The goal of the Connectivity Monitoring Object is to carry information reflecting the more up to date values of the current connection for monitoring purposes. Resources such as Link Quality, Radio Signal Strength, Cell ID are retrieved during connected mode at least for cellular networks. - - 4 - urn:oma:lwm2m:oma:4 - 1.0 - 1.0 - Single - Optional - - - Network Bearer - R - Single - Mandatory - Integer - 0-50 - - - Indicates the network bearer used for the current LwM2M communication session from the network bearer list below. The number range is split into three categories: 0 - 20 are Cellular Bearers 21 - 40 are Wireless Bearers 41 - 50 are Wireline Bearers More specifically: 0: GSM cellular network 1: TD-SCDMA cellular network 2: WCDMA cellular network 3: CDMA2000 cellular network 4: WiMAX cellular network 5: LTE-TDD cellular network 6: LTE-FDD cellular network 7: NB-IoT 8 - 20: Reserved for other types of cellular network 21: WLAN network 22: Bluetooth network 23: IEEE 802.15.4 network 24 - 40: Reserved for other types of local wireless network 41: Ethernet 42: DSL 43: PLC 44 - 50: reserved for other types of wireline networks. - - - - Available Network Bearer - R - Multiple - Mandatory - Integer - 0-50 - - - Indicates a list of current available network bearer. Each Resource Instance has a value from the network bearer list. - - - - Radio Signal Strength - R - Single - Mandatory - Integer - - dBm - - Indicates the average value of the received signal strength indication used in the current network bearer (as indicated by Resource 0 of this Object). For the following network bearers the signal strength parameters indicated below are represented by this resource: GSM: RSSI UMTS: RSCP LTE: RSRP NB-IoT: NRSRP For more details on Network Measurement Report, refer to the appropriate Cellular or Wireless Network standards, (e.g. for LTE Cellular Network refer to 3GPP TS 36.133 specification). - - - - Link Quality - R - Single - Optional - Integer - - - - This contains received link quality e.g. LQI for IEEE 802.15.4 (range 0...255), RxQual Downlink for GSM (range 0...7, refer to [3GPP 44.018] for more details on Network Measurement Report encoding), RSRQ for LTE, (refer to [3GPP 36.214]), NRSRQ for NB-IoT (refer to [3GPP 36.214]). - - - - IP Addresses - R - Multiple - Mandatory - String - - - - The IP addresses assigned to the connectivity interface. (e.g. IPv4, IPv6, etc.) - - - - Router IP Addresses - R - Multiple - Optional - String - - - - The IP address of the next-hop IP router, on each of the interfaces specified in resource 4 (IP Addresses). Note: This IP Address doesn’t indicate the Server IP address. - - - - Link Utilization - R - Single - Optional - Integer - 0-100 - % - - The percentage indicating the average utilization of the link to the next-hop IP router. - - - - APN - R - Multiple - Optional - String - - - - Access Point Name in case Network Bearer Resource is a Cellular Network. - - - - Cell ID - R - Single - Optional - Integer - - - - Serving Cell ID in case Network Bearer Resource is a Cellular Network. As specified in TS [3GPP 23.003] and in [3GPP. 24.008]. Range (0...65535) in GSM/EDGE UTRAN Cell ID has a length of 28 bits. Cell Identity in WCDMA/TD-SCDMA. Range: (0...268435455). LTE Cell ID has a length of 28 bits. Parameter definitions in [3GPP 25.331]. - - - - SMNC - R - Single - Optional - Integer - 0-999 - % - - Serving Mobile Network Code. This is applicable when the Network Bearer Resource value is referring to a cellular network. As specified in TS [3GPP 23.003]. - - - - SMCC - R - Single - Optional - Integer - 0-999 - - - Serving Mobile Country Code. This is applicable when the Network Bearer Resource value is referring to a cellular network. As specified in TS [3GPP 23.003]. - - - - - - diff --git a/common/transport/lwm2m/src/main/resources/models/LwM2M_BinaryAppDataContainer-v1_0_1.xml b/common/transport/lwm2m/src/main/resources/models/LwM2M_BinaryAppDataContainer-v1_0_1.xml deleted file mode 100644 index b111d3b321..0000000000 --- a/common/transport/lwm2m/src/main/resources/models/LwM2M_BinaryAppDataContainer-v1_0_1.xml +++ /dev/null @@ -1,147 +0,0 @@ - - - - - BinaryAppDataContainer - - 19 - urn:oma:lwm2m:oma:19 - 1.0 - 1.0 - Multiple - Optional - - Data - RW - - - - Multiple - Mandatory - Opaque - - - - - Data Priority - RW - Single - Optional - Integer - 1 bytes - - - - Data Creation Time - RW - Single - Optional - Time - - - - - Data Description - RW - Single - Optional - String - 32 bytes - - - - Data Format - RW - Single - Optional - String - 32 bytes - - - - App ID - RW - Single - Optional - Integer - 2 bytes - - - - - - diff --git a/common/transport/transport-api/pom.xml b/common/transport/transport-api/pom.xml index 87a4562f81..77709c3ddc 100644 --- a/common/transport/transport-api/pom.xml +++ b/common/transport/transport-api/pom.xml @@ -114,9 +114,12 @@ org.eclipse.leshan leshan-core - 1.0.1 compile + + org.eclipse.leshan + leshan-server-cf + diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/TransportContext.java b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/TransportContext.java index 4b7677dd69..760431b250 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/TransportContext.java +++ b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/TransportContext.java @@ -43,8 +43,10 @@ public abstract class TransportContext { @Autowired private TransportService transportService; + @Autowired private TbServiceInfoProvider serviceInfoProvider; + @Autowired private SchedulerComponent scheduler; diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/TransportService.java b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/TransportService.java index cec9eba5a1..d676874458 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/TransportService.java +++ b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/TransportService.java @@ -19,7 +19,7 @@ import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceTransportType; import org.thingsboard.server.common.transport.auth.GetOrCreateDeviceFromGatewayResponse; import org.thingsboard.server.common.transport.auth.ValidateDeviceCredentialsResponse; -import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.common.transport.service.SessionMetaData; import org.thingsboard.server.gen.transport.TransportProtos.ClaimDeviceMsg; import org.thingsboard.server.gen.transport.TransportProtos.GetAttributeRequestMsg; import org.thingsboard.server.gen.transport.TransportProtos.GetEntityProfileRequestMsg; @@ -98,7 +98,7 @@ public interface TransportService { void registerSyncSession(SessionInfoProto sessionInfo, SessionMsgListener listener, long timeout); - void reportActivity(SessionInfoProto sessionInfo); + SessionMetaData reportActivity(SessionInfoProto sessionInfo); void deregisterSession(SessionInfoProto sessionInfo); } diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/adaptor/JsonConverter.java b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/adaptor/JsonConverter.java index a20f697bba..d745ebeb65 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/adaptor/JsonConverter.java +++ b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/adaptor/JsonConverter.java @@ -59,7 +59,6 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; -import java.util.UUID; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -426,6 +425,8 @@ public class JsonConverter { case MQTT_BASIC: result.add("credentialsValue", JSON_PARSER.parse(payload.getCredentialsValue()).getAsJsonObject()); break; + case LWM2M_CREDENTIALS: + break; } result.addProperty("credentialsType", payload.getCredentialsType().name()); result.addProperty("status", ProvisionResponseStatus.SUCCESS.name()); diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/lwm2m/LwM2MTransportConfigBootstrap.java b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/lwm2m/LwM2MTransportConfigBootstrap.java index 2e8a00bc5e..286f555c0c 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/lwm2m/LwM2MTransportConfigBootstrap.java +++ b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/lwm2m/LwM2MTransportConfigBootstrap.java @@ -24,7 +24,6 @@ import org.springframework.stereotype.Component; import org.thingsboard.server.gen.transport.TransportProtos; import java.security.PublicKey; -import java.security.cert.X509Certificate; import java.util.Map; @Slf4j @@ -32,39 +31,57 @@ import java.util.Map; @ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true') || '${service.type:null}'=='monolith' || '${service.type:null}'=='tb-core'") public class LwM2MTransportConfigBootstrap { - @Getter - @Value("${transport.lwm2m.bootstrap.bind_address:}") - private String bootstrapHost; + @Value("${transport.lwm2m.bootstrap.enable:}") + private Boolean bootstrapEnable; @Getter - @Value("${transport.lwm2m.bootstrap.bind_port:}") - private Integer bootstrapPort; + @Value("${transport.lwm2m.bootstrap.id:}") + private Integer bootstrapServerId; @Getter - @Value("${transport.lwm2m.bootstrap.bind_port_cert:}") - private Integer bootstrapPortCert; + @Value("${transport.lwm2m.bootstrap.secure.start_psk:}") + private Boolean bootstrapStartPsk; + @Getter + @Value("${transport.lwm2m.bootstrap.secure.start_rpk:}") + private Boolean bootstrapStartRpk; @Getter - @Value("${transport.lwm2m.bootstrap.secure.start_all:}") - private boolean bootstrapStartAll; + @Value("${transport.lwm2m.bootstrap.secure.start_x509:}") + private Boolean bootstrapStartX509; @Getter - @Value("${transport.lwm2m.bootstrap.secure.dtls_mode:}") - private Integer bootStrapDtlsMode; + @Value("${transport.lwm2m.bootstrap.bind_address:}") + private String bootstrapHost; @Getter @Value("${transport.lwm2m.bootstrap.secure.bind_address:}") private String bootstrapSecureHost; @Getter - @Value("${transport.lwm2m.bootstrap.secure.bind_port:}") - private Integer bootstrapSecurePort; + @Value("${transport.lwm2m.bootstrap.bind_port_no_sec_psk:}") + private Integer bootstrapPortNoSecPsk; + + @Getter + @Value("${transport.lwm2m.bootstrap.bind_port_no_sec_rpk:}") + private Integer bootstrapPortNoSecRpk; @Getter - @Value("${transport.lwm2m.bootstrap.secure.bind_port_cert:}") - private Integer bootstrapSecurePortCert; + @Value("${transport.lwm2m.bootstrap.bind_port_no_sec_x509:}") + private Integer bootstrapPortNoSecX509; + + @Getter + @Value("${transport.lwm2m.bootstrap.secure.bind_port_psk:}") + private Integer bootstrapSecurePortPsk; + + @Getter + @Value("${transport.lwm2m.bootstrap.secure.bind_port_rpk:}") + private Integer bootstrapSecurePortRpk; + + @Getter + @Value("${transport.lwm2m.bootstrap.secure.bind_port_x509:}") + private Integer bootstrapSecurePortX509; @Getter @Value("${transport.lwm2m.bootstrap.secure.public_x:}") @@ -86,10 +103,6 @@ public class LwM2MTransportConfigBootstrap { @Value("${transport.lwm2m.bootstrap.secure.alias:}") private String bootstrapAlias; - @Getter - @Setter - private X509Certificate bootstrapCertificate; - @Getter @Setter private Map sessions; diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/lwm2m/LwM2MTransportConfigServer.java b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/lwm2m/LwM2MTransportConfigServer.java index d8f305a049..9d3e199aea 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/lwm2m/LwM2MTransportConfigServer.java +++ b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/lwm2m/LwM2MTransportConfigServer.java @@ -20,32 +20,33 @@ import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.eclipse.leshan.core.model.ObjectLoader; import org.eclipse.leshan.core.model.ObjectModel; +import org.eclipse.leshan.core.model.ResourceModel; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.server.registration.Registration; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; +import java.util.Arrays; import java.util.List; +import java.util.stream.Collectors; @Slf4j @Component @ConditionalOnExpression("('${service.type:null}'=='tb-transport' && '${transport.lwm2m.enabled:false}'=='true') || '${service.type:null}'=='monolith' || '${service.type:null}'=='tb-core'") public class LwM2MTransportConfigServer { - @Getter - @Value("${transport.lwm2m.timeout:}") - private Long timeout; - - @Getter - @Value("${transport.sessions.report_timeout}") - private long sessionReportTimeout; @Getter private String MODEL_PATH_DEFAULT = "models"; @@ -77,10 +78,6 @@ public class LwM2MTransportConfigServer { @Getter private String BASE_DIR_PATH = System.getProperty("user.dir"); - @Getter - @Value("${transport.lwm2m.model_path_file:}") - private String modelPathFile; - @Getter // private String PATH_DATA_MICROSERVICE = "/usr/share/tb-lwm2m-transport/data$"; private String PATH_DATA = "data"; @@ -90,8 +87,44 @@ public class LwM2MTransportConfigServer { private List modelsValue; @Getter - @Value("${transport.lwm2m.support_deprecated_ciphers_enable:}") - private boolean supportDeprecatedCiphersEnable; + @Value("${transport.lwm2m.timeout:}") + private Long timeout; + + @Getter + @Value("${transport.sessions.report_timeout}") + private long sessionReportTimeout; + + @Getter + @Value("${transport.lwm2m.model_path_file:}") + private String modelPathFile; + + @Getter + @Value("${transport.lwm2m.recommended_ciphers:}") + private boolean recommendedCiphers; + + @Getter + @Value("${transport.lwm2m.recommended_supported_groups:}") + private boolean recommendedSupportedGroups; + + @Getter + @Value("${transport.lwm2m.request_pool_size:}") + private int requestPoolSize; + + @Getter + @Value("${transport.lwm2m.request_error_pool_size:}") + private int requestErrorPoolSize; + + @Getter + @Value("${transport.lwm2m.registered_pool_size:}") + private int registeredPoolSize; + + @Getter + @Value("${transport.lwm2m.update_registered_pool_size:}") + private int updateRegisteredPoolSize; + + @Getter + @Value("${transport.lwm2m.un_registered_pool_size:}") + private int unRegisteredPoolSize; @Getter @Value("${transport.lwm2m.secure.key_store_type:}") @@ -113,6 +146,18 @@ public class LwM2MTransportConfigServer { @Value("${transport.lwm2m.secure.root_alias:}") private String rootAlias; + @Getter + @Value("${transport.lwm2m.server.secure.start_psk:}") + private boolean serverStartPsk; + + @Getter + @Value("${transport.lwm2m.server.secure.start_rpk:}") + private boolean serverStartRpk; + + @Getter + @Value("${transport.lwm2m.server.secure.start_x509:}") + private boolean serverStartX509; + @Getter @Value("${transport.lwm2m.secure.enable_gen_psk_rpk:}") private Boolean enableGenPskRpk; @@ -122,32 +167,37 @@ public class LwM2MTransportConfigServer { private String serverHost; @Getter - @Value("${transport.lwm2m.server.bind_port:}") - private Integer serverPort; + @Value("${transport.lwm2m.server.id:}") + private Integer serverId; + + @Getter + @Value("${transport.lwm2m.server.secure.bind_address:}") + private String serverSecureHost; + @Getter - @Value("${transport.lwm2m.server.bind_port_cert:}") - private Integer serverPortCert; + @Value("${transport.lwm2m.server.bind_port_no_sec_psk:}") + private Integer serverPortNoSecPsk; @Getter - @Value("${transport.lwm2m.server.secure.start_all:}") - private boolean serverStartAll; + @Value("${transport.lwm2m.server.bind_port_no_sec_rpk:}") + private Integer serverPortNoSecRpk; @Getter - @Value("${transport.lwm2m.server.secure.dtls_mode:}") - private Integer serverDtlsMode; + @Value("${transport.lwm2m.server.bind_port_no_sec_x509:}") + private Integer serverPortNoSecX509; @Getter - @Value("${transport.lwm2m.server.secure.bind_address:}") - private String serverSecureHost; + @Value("${transport.lwm2m.server.secure.bind_port_psk:}") + private Integer serverPortPsk; @Getter - @Value("${transport.lwm2m.server.secure.bind_port:}") - private Integer serverSecurePort; + @Value("${transport.lwm2m.server.secure.bind_port_rpk:}") + private Integer serverPortRpk; @Getter - @Value("${transport.lwm2m.server.secure.bind_port_cert:}") - private Integer serverSecurePortCert; + @Value("${transport.lwm2m.server.secure.bind_port_x509:}") + private Integer serverPortX509; @Getter @Value("${transport.lwm2m.server.secure.public_x:}") @@ -165,10 +215,6 @@ public class LwM2MTransportConfigServer { @Value("${transport.lwm2m.server.secure.alias:}") private String serverAlias; - @Getter - @Value("${transport.lwm2m.bootstrap.enable:}") - private Boolean bootstrapEnable; - @Getter @Value("${transport.lwm2m.secure.redis_url:}") private String redisUrl; @@ -187,7 +233,7 @@ public class LwM2MTransportConfigServer { } else { log.error(" [{}] Read Models", path.getAbsoluteFile()); } - getInKeyStore(); + this.getInKeyStore(); } private File getPathModels() { @@ -238,4 +284,26 @@ public class LwM2MTransportConfigServer { } return FULL_FILE_PATH.toUri().getPath(); } + + public ResourceModel getResourceModel(Registration registration, LwM2mPath pathIds) { + String pathLink = "/" + pathIds.getObjectId() + "/" + pathIds.getObjectInstanceId(); + return (Arrays.stream(registration.getObjectLinks()).filter(p-> p.getUrl().equals(pathLink)).findFirst().isPresent() && + this.modelsValue.stream().filter(v -> v.id == pathIds.getObjectId()).collect(Collectors.toList()).size() > 0) && + this.modelsValue.stream().filter(v -> v.id == pathIds.getObjectId()).collect(Collectors.toList()).get(0).resources.containsKey(pathIds.getResourceId()) ? + this.modelsValue.stream().filter(v -> v.id == pathIds.getObjectId()).collect(Collectors.toList()).get(0).resources.get(pathIds.getResourceId()) : + null; + } + + public ResourceModel.Type getResourceModelType(Registration registration, LwM2mPath pathIds) { + ResourceModel resource = this.getResourceModel(registration, pathIds); + return (resource == null) ? null : resource.type; + } + + public ResourceModel.Operations getOperation(Registration registration, LwM2mPath pathIds) { + ResourceModel resource = this.getResourceModel(registration, pathIds); + return (resource == null) ? ResourceModel.Operations.NONE : resource.operations; + } + + + } diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/DefaultTransportService.java b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/DefaultTransportService.java index 246ad7c7c0..3a4790e58a 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/DefaultTransportService.java +++ b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/DefaultTransportService.java @@ -509,8 +509,8 @@ public class DefaultTransportService implements TransportService { } @Override - public void reportActivity(TransportProtos.SessionInfoProto sessionInfo) { - reportActivityInternal(sessionInfo); + public SessionMetaData reportActivity(TransportProtos.SessionInfoProto sessionInfo) { + return reportActivityInternal(sessionInfo); } private SessionMetaData reportActivityInternal(TransportProtos.SessionInfoProto sessionInfo) { diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/SessionMetaData.java b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/SessionMetaData.java index ac293307a9..dba3338d67 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/SessionMetaData.java +++ b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/SessionMetaData.java @@ -25,6 +25,7 @@ import java.util.concurrent.ScheduledFuture; * Created by ashvayka on 15.10.18. */ @Data +public class SessionMetaData { private volatile TransportProtos.SessionInfoProto sessionInfo; diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsServiceImpl.java index ff1763f662..db123746ab 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsServiceImpl.java @@ -21,7 +21,6 @@ import org.hibernate.exception.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.thingsboard.server.common.data.Device; @@ -87,6 +86,9 @@ public class DeviceCredentialsServiceImpl extends AbstractEntityService implemen case MQTT_BASIC: formatSimpleMqttCredentials(deviceCredentials); break; + case LWM2M_CREDENTIALS: + formatSimpleLwm2mCredentials(deviceCredentials); + break; } log.trace("Executing updateDeviceCredentials [{}]", deviceCredentials); credentialsValidator.validate(deviceCredentials, id -> tenantId); @@ -129,6 +131,7 @@ public class DeviceCredentialsServiceImpl extends AbstractEntityService implemen deviceCredentials.setCredentialsValue(JacksonUtil.toString(mqttCredentials)); } + private void formatCertData(DeviceCredentials deviceCredentials) { String cert = EncryptionUtil.trimNewLines(deviceCredentials.getCredentialsValue()); String sha3Hash = EncryptionUtil.getSha3Hash(cert); @@ -136,6 +139,10 @@ public class DeviceCredentialsServiceImpl extends AbstractEntityService implemen deviceCredentials.setCredentialsValue(cert); } + private void formatSimpleLwm2mCredentials(DeviceCredentials deviceCredentials) { + + } + @Override @CacheEvict(cacheNames = DEVICE_CREDENTIALS_CACHE, key = "'deviceCredentials_' + #deviceCredentials.credentialsId") public void deleteDeviceCredentials(TenantId tenantId, DeviceCredentials deviceCredentials) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java index a919f86dfe..a35691160c 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java @@ -177,10 +177,40 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe return doSaveDevice(device, null); } + @CacheEvict(cacheNames = DEVICE_CACHE, key = "{#device.tenantId, #device.name}") + @Override + public Device saveDeviceWithCredentials(Device device, DeviceCredentials deviceCredentials) { + if (device.getId() == null) { + Device deviceWithName = this.findDeviceByTenantIdAndName(device.getTenantId(), device.getName()); + device = deviceWithName == null ? device : deviceWithName.updateDevice(device); + } + Device savedDevice = this.saveDeviceWithoutCredentials(device); + deviceCredentials.setDeviceId(savedDevice.getId()); + if (device.getId() == null) { + deviceCredentials = deviceCredentialsService.createDeviceCredentials(savedDevice.getTenantId(), deviceCredentials); + } + else { + deviceCredentials.setId(deviceCredentialsService.findDeviceCredentialsByDeviceId(device.getTenantId(), savedDevice.getId()).getId()); + deviceCredentials = deviceCredentialsService.updateDeviceCredentials(device.getTenantId(), deviceCredentials); + } + return savedDevice; + } + private Device doSaveDevice(Device device, String accessToken) { + Device savedDevice = this.saveDeviceWithoutCredentials(device); + if (device.getId() == null) { + DeviceCredentials deviceCredentials = new DeviceCredentials(); + deviceCredentials.setDeviceId(new DeviceId(savedDevice.getUuidId())); + deviceCredentials.setCredentialsType(DeviceCredentialsType.ACCESS_TOKEN); + deviceCredentials.setCredentialsId(!StringUtils.isEmpty(accessToken) ? accessToken : RandomStringUtils.randomAlphanumeric(20)); + deviceCredentialsService.createDeviceCredentials(device.getTenantId(), deviceCredentials); + } + return savedDevice; + } + + private Device saveDeviceWithoutCredentials(Device device) { log.trace("Executing saveDevice [{}]", device); deviceValidator.validate(device, Device::getTenantId); - Device savedDevice; try { DeviceProfile deviceProfile; if (device.getDeviceProfileId() == null) { @@ -198,8 +228,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe } device.setType(deviceProfile.getName()); device.setDeviceData(syncDeviceData(deviceProfile, device.getDeviceData())); - - savedDevice = deviceDao.save(device.getTenantId(), device); + return deviceDao.save(device.getTenantId(), device); } catch (Exception t) { ConstraintViolationException e = extractConstraintViolationException(t).orElse(null); if (e != null && e.getConstraintName() != null && e.getConstraintName().equalsIgnoreCase("device_name_unq_key")) { @@ -208,14 +237,6 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe throw t; } } - if (device.getId() == null) { - DeviceCredentials deviceCredentials = new DeviceCredentials(); - deviceCredentials.setDeviceId(new DeviceId(savedDevice.getUuidId())); - deviceCredentials.setCredentialsType(DeviceCredentialsType.ACCESS_TOKEN); - deviceCredentials.setCredentialsId(!StringUtils.isEmpty(accessToken) ? accessToken : RandomStringUtils.randomAlphanumeric(20)); - deviceCredentialsService.createDeviceCredentials(device.getTenantId(), deviceCredentials); - } - return savedDevice; } private DeviceData syncDeviceData(DeviceProfile deviceProfile, DeviceData deviceData) { @@ -512,6 +533,8 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe case X509_CERTIFICATE: deviceCredentials.setCredentialsValue(provisionRequest.getCredentialsData().getX509CertHash()); break; + case LWM2M_CREDENTIALS: + break; } try { deviceCredentialsService.updateDeviceCredentials(savedDevice.getTenantId(), deviceCredentials); @@ -528,7 +551,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @Override protected void validateCreate(TenantId tenantId, Device device) { DefaultTenantProfileConfiguration profileConfiguration = - (DefaultTenantProfileConfiguration)tenantProfileCache.get(tenantId).getProfileData().getConfiguration(); + (DefaultTenantProfileConfiguration) tenantProfileCache.get(tenantId).getProfileData().getConfiguration(); long maxDevices = profileConfiguration.getMaxDevices(); validateNumberOfEntitiesPerTenant(tenantId, deviceDao, maxDevices, EntityType.DEVICE); } diff --git a/netty-mqtt/pom.xml b/netty-mqtt/pom.xml index 793ea83373..bcf36485a9 100644 --- a/netty-mqtt/pom.xml +++ b/netty-mqtt/pom.xml @@ -67,11 +67,6 @@ org.apache.maven.plugins maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - org.apache.maven.plugins @@ -87,4 +82,4 @@ - \ No newline at end of file + diff --git a/pom.xml b/pom.xml index d87cc038d5..6fc9e94051 100755 --- a/pom.xml +++ b/pom.xml @@ -62,9 +62,10 @@ 2.11.3 2.11.3 2.2.6 - 2.2.3 - 1.0.1 - 1.0.0 + 2.6.0 + 1.3.0 + 1.3.0 + 1.3.0 2.6.2 2.3.30 1.6.2 @@ -578,7 +579,7 @@ org.apache.maven.plugins maven-compiler-plugin - 2.5.1 + 3.8.1 1.8 1.8 @@ -1160,11 +1161,30 @@ leshan-server-redis ${leshan-server.version} + + org.eclipse.leshan + leshan-core + ${leshan-core.version} + + + org.eclipse.californium + californium-core + ${californium.version} + test-jar + test + org.eclipse.californium californium-core ${californium.version} + + org.eclipse.californium + element-connector + ${californium.version} + test-jar + test + com.google.code.gson gson diff --git a/rest-client/src/main/java/org/thingsboard/rest/client/RestClient.java b/rest-client/src/main/java/org/thingsboard/rest/client/RestClient.java index e79bb2b713..17fd9c83c5 100644 --- a/rest-client/src/main/java/org/thingsboard/rest/client/RestClient.java +++ b/rest-client/src/main/java/org/thingsboard/rest/client/RestClient.java @@ -121,6 +121,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -1091,6 +1092,24 @@ public class RestClient implements ClientHttpRequestInterceptor, Closeable { return restTemplate.postForEntity(baseURL + "/api/device/credentials", deviceCredentials, DeviceCredentials.class).getBody(); } + public Optional saveDeviceWithCredentials(Device device, DeviceCredentials credentials) { + try { + Map, Object> deviceCredentials = new ConcurrentHashMap<>(); + deviceCredentials.put(Device.class, device); + deviceCredentials.put(DeviceCredentials.class, credentials); +// return restTemplate.postForEntity(baseURL + "/api/lwm2m/device-credentials", deviceCredentials, Device.class).getBody(); + ResponseEntity deviceOpt = restTemplate.postForEntity(baseURL + "/api/lwm2m/device-credentials", deviceCredentials, Device.class); + return Optional.ofNullable(deviceOpt.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public PageData getTenantDevices(String type, PageLink pageLink) { Map params = new HashMap<>(); params.put("type", type); diff --git a/transport/lwm2m/pom.xml b/transport/lwm2m/pom.xml index 60a2d29d58..addbeb9d7b 100644 --- a/transport/lwm2m/pom.xml +++ b/transport/lwm2m/pom.xml @@ -45,11 +45,38 @@ + + org.thingsboard.common.transport + transport-api + + + org.springframework + spring-context-support + + + org.springframework + spring-context + + + org.slf4j + slf4j-api + + + org.slf4j + log4j-over-slf4j + + + ch.qos.logback + logback-core + + + ch.qos.logback + logback-classic + org.eclipse.leshan leshan-server-cf - org.eclipse.leshan leshan-client-cf @@ -59,7 +86,6 @@ org.eclipse.leshan leshan-server-redis - org.springframework.boot spring-boot-starter-test @@ -78,37 +104,23 @@ org.eclipse.californium californium-core - ${californium.version} test-jar test + + org.eclipse.californium + californium-core + + + + + org.eclipse.californium element-connector - ${californium.version} test-jar test - - - org.thingsboard.common.transport - lwm2m - - - org.thingsboard.common - queue - - - org.springframework.boot - spring-boot-starter-web - - - com.sun.winsw - winsw - bin - exe - provided - diff --git a/transport/lwm2m/src/main/data/credentials/serverKeyStore.jks b/transport/lwm2m/src/main/data/credentials/serverKeyStore.jks index b5b6c9fa3c..9336dd1168 100644 Binary files a/transport/lwm2m/src/main/data/credentials/serverKeyStore.jks and b/transport/lwm2m/src/main/data/credentials/serverKeyStore.jks differ diff --git a/transport/lwm2m/src/main/data/credentials/shell/lwM2M_credentials.sh b/transport/lwm2m/src/main/data/credentials/shell/lwM2M_credentials.sh new file mode 100755 index 0000000000..6a1ad298ac --- /dev/null +++ b/transport/lwm2m/src/main/data/credentials/shell/lwM2M_credentials.sh @@ -0,0 +1,403 @@ +#!/bin/bash +# +# Copyright © 2016-2020 The Thingsboard Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +#p) CLIENT_CN=LwX50900000000 +#s) client_start=0 +#f) client_finish=1 +#a) CLIENT_ALIAS=client_alias_00000000 +#b) BOOTSTRAP_ALIAS=bootstrap +#d) SERVER_ALIAS=server +#j) SERVER_STORE=serverKeyStore.jks +#k) CLIENT_STORE=clientKeyStore.jks +#c) CLIENT_STORE_PWD=client_ks_password +#w) SERVER_STORE_PWD=server_ks_password + +#while test $# -gt 0; do +# case "$1" in +# -h|--help) +# echo "$package - attempt to capture frames" +# echo " " +# echo "$package [options] application [arguments]" +# echo " " +# echo "options:" +# echo "-h, --help show brief help" +# echo "-a, --action=ACTION specify an action to use" +# echo "-o, --output-dir=DIR specify a directory to store output in" +# exit 0 +# ;; +# -a) +# shift +# if test $# -gt 0; then +# export PROCESS=$1 +# else +# echo "no process specified" +# exit 1 +# fi +# shift +# ;; +# --action*) +# export PROCESS=`echo $1 | sed -e 's/^[^=]*=//g'` +# shift +# ;; +# -o) +# shift +# if test $# -gt 0; then +# export OUTPUT=$1 +# else +# echo "no output dir specified" +# exit 1 +# fi +# shift +# ;; +# --output-dir*) +# export OUTPUT=`echo $1 | sed -e 's/^[^=]*=//g'` +# shift +# ;; +# *) +# break +# ;; +# esac +#done + + +while getopts p:s:f:a:b:d:j:k:c:w: flag; do + case "${flag}" in + p) client_prefix=${OPTARG} ;; + s) client_start=${OPTARG} ;; + f) client_finish=${OPTARG} ;; + a) client_alias=${OPTARG} ;; + b) bootstrap_alias=${OPTARG} ;; + d) server_alias=${OPTARG} ;; + j) key_store_server_file=${OPTARG} ;; + k) key_store_client_file=${OPTARG} ;; + c) client_key_store_pwd=${OPTARG} ;; + w) server_key_store_pwd=${OPTARG} ;; + esac +done + +# cd to dir of script +script_dir=$(dirname $0) +echo "script_dir: $script_dir" +cd $script_dir +# source the properties: +. ./lwM2M_keygen.properties + + +if [ -n "$client_prefix" ]; then + CLIENT_PREFIX=$client_prefix +fi + +if [ -z "$client_start" ]; then + client_start=0 +fi + +if [ -z "$client_finish" ]; then + client_finish=1 +fi + +if [ -n "$client_alias" ]; then + CLIENT_ALIAS=$client_alias +fi + +if [ -n "$bootstrap_alias" ]; then + BOOTSTRAP_ALIAS=$bootstrap_alias +fi + +if [ -n "$server_alias" ]; then + SERVER_ALIAS=$server_alias +fi + +if [ -n "$key_store_server_file" ]; then + SERVER_STORE=$key_store_server_file +fi + +if [ -n "$key_store_client_file" ]; then + CLIENT_STORE=$key_store_client_file +fi + +if [ -n "$client_key_store_pwd" ]; then + CLIENT_STORE_PWD=$client_key_store_pwd +fi + +if [ -n "$server_key_store_pwd" ]; then + SERVER_STORE_PWD=$server_key_store_pwd +fi + +echo "==Start==" +echo "CLIENT_PREFIX: $CLIENT_PREFIX" +echo "client_start: $client_start" +echo "client_finish: $client_finish" +echo "CLIENT_ALIAS: $CLIENT_ALIAS" +echo "BOOTSTRAP_ALIAS: $BOOTSTRAP_ALIAS" +echo "SERVER_ALIAS: $SERVER_ALIAS" +echo "SERVER_STORE: $SERVER_STORE" +echo "CLIENT_STORE: $CLIENT_STORE" +echo "CLIENT_STORE_PWD: $CLIENT_STORE_PWD" +echo "SERVER_STORE_PWD: $SERVER_STORE_PWD" + +end_point() { + echo "$CLIENT_PREFIX$(printf "%08d" $CLIENT_NUMBER)" +} +client_alias_point() { + echo "$CLIENT_ALIAS$(printf "%08d" $CLIENT_NUMBER)" +} + +# Generation of the keystore. +echo "${H0}====START========${RESET}" +echo "${H1}Server Keystore : ${RESET}" +echo "${H1}==================${RESET}" +echo "${H2}Creating the trusted root CA key and certificate...${RESET}" +# -keysize +# 1024 (when using -genkeypair) +keytool \ + -genkeypair \ + -alias $ROOT_KEY_ALIAS \ + -keyalg EC \ + -dname "CN=$ROOT_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ + -validity $VALIDITY \ + -storetype $STORETYPE \ + -keypass $SERVER_STORE_PWD \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD + +echo +echo "${H2}Creating server key and self-signed certificate ...${RESET}" +keytool \ + -genkeypair \ + -alias $SERVER_ALIAS \ + -keyalg EC \ + -dname "CN=$SERVER_SELF_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ + -validity $VALIDITY \ + -storetype $STORETYPE \ + -keypass $SERVER_STORE_PWD \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD +keytool \ + -exportcert \ + -alias $SERVER_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD | + keytool \ + -importcert \ + -alias $SERVER_SELF_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD \ + -noprompt + +echo +echo "${H2}Creating server certificate signed by root CA...${RESET}" +keytool \ + -certreq \ + -alias $SERVER_ALIAS \ + -dname "CN=$SERVER_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD | + keytool \ + -gencert \ + -alias $ROOT_KEY_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD \ + -storetype $STORETYPE \ + -validity $VALIDITY | + keytool \ + -importcert \ + -alias $SERVER_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD + +echo +echo "${H2}Creating bootstrap key and self-signed certificate ...${RESET}" +keytool \ + -genkeypair \ + -alias $BOOTSTRAP_ALIAS \ + -keyalg EC \ + -dname "CN=$BOOTSTRAP_SELF_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ + -validity $VALIDITY \ + -storetype $STORETYPE \ + -keypass $SERVER_STORE_PWD \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD +keytool \ + -exportcert \ + -alias $BOOTSTRAP_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD | + keytool \ + -importcert \ + -alias $BOOTSTRAP_SELF_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD \ + -noprompt + +echo +echo "${H2}Creating bootstrap certificate signed by root CA...${RESET}" +keytool \ + -certreq \ + -alias $BOOTSTRAP_ALIAS \ + -dname "CN=$BOOTSTRAP_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD | + keytool \ + -gencert \ + -alias $ROOT_KEY_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD \ + -storetype $STORETYPE \ + -validity $VALIDITY | + keytool \ + -importcert \ + -alias $BOOTSTRAP_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD + +echo +echo "${H1}Client Keystore : ${RESET}" +echo "${H1}==================${RESET}" +#echo "${H2}Creating client key and self-signed certificate with expected CN...${RESET}" +#keytool \ +# -genkeypair \ +# -alias $CLIENT_ALIAS \ +# -keyalg EC \ +# -dname "CN=$CLIENT_SELF_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ +# -validity $VALIDITY \ +# -storetype $STORETYPE \ +# -keypass $CLIENT_STORE_PWD \ +# -keystore $CLIENT_STORE \ +# -storepass $CLIENT_STORE_PWD +#keytool \ +# -exportcert \ +# -alias $CLIENT_ALIAS \ +# -keystore $CLIENT_STORE \ +# -storepass $CLIENT_STORE_PWD | \ +# keytool \ +# -importcert \ +# -alias $CLIENT_SELF_ALIAS \ +# -keystore $CLIENT_STORE \ +# -storepass $CLIENT_STORE_PWD \ +# -noprompt + +echo +echo "${H2}Import root certificate just to be able to import need by root CA with expected CN...${RESET}" +keytool \ + -exportcert \ + -alias $ROOT_KEY_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD | + keytool \ + -importcert \ + -alias $ROOT_KEY_ALIAS \ + -keystore $CLIENT_STORE \ + -storepass $CLIENT_STORE_PWD \ + -noprompt + +#echo +#echo "${H2}Creating client certificate signed by root CA with expected CN...${RESET}" +#keytool \ +# -certreq \ +# -alias $CLIENT_ALIAS \ +# -dname "CN=$CLIENT_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ +# -keystore $CLIENT_STORE \ +# -storepass $CLIENT_STORE_PWD | \ +# keytool \ +# -gencert \ +# -alias $ROOT_KEY_ALIAS \ +# -keystore $SERVER_STORE \ +# -storepass $SERVER_STORE_PWD \ +# -storetype $STORETYPE \ +# -validity $VALIDITY | \ +# keytool \ +# -importcert \ +# -alias $CLIENT_ALIAS \ +# -keystore $CLIENT_STORE \ +# -storepass $CLIENT_STORE_PWD \ +# -noprompt + +cert_end_point() { + echo "${H2}Creating client key and self-signed certificate with expected CN $CLIENT_SELF_CN ${RESET}" + keytool \ + -genkeypair \ + -alias $CLIENT_CN_ALIAS \ + -keyalg EC \ + -dname "CN=$CLIENT_SELF_CN, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ + -validity $VALIDITY \ + -storetype $STORETYPE \ + -keypass $CLIENT_STORE_PWD \ + -keystore $CLIENT_STORE \ + -storepass $CLIENT_STORE_PWD + keytool \ + -exportcert \ + -alias $CLIENT_CN_ALIAS \ + -keystore $CLIENT_STORE \ + -storepass $CLIENT_STORE_PWD | + keytool \ + -importcert \ + -alias $CLIENT_SELF_ALIAS \ + -keystore $CLIENT_STORE \ + -storepass $CLIENT_STORE_PWD \ + -noprompt + + echo + echo "${H2}Creating client certificate signed by root CA with expected $CLIENT_CN_NAME ${RESET}" + keytool \ + -certreq \ + -alias $CLIENT_CN_ALIAS \ + -dname "CN=$CLIENT_CN_NAME, OU=$ORGANIZATIONAL_UNIT, O=$ORGANIZATION, L=$CITY, ST=$STATE_OR_PROVINCE, C=$TWO_LETTER_COUNTRY_CODE" \ + -keystore $CLIENT_STORE \ + -storepass $CLIENT_STORE_PWD | + keytool \ + -gencert \ + -alias $ROOT_KEY_ALIAS \ + -keystore $SERVER_STORE \ + -storepass $SERVER_STORE_PWD \ + -storetype $STORETYPE \ + -validity $VALIDITY | + keytool \ + -importcert \ + -alias $CLIENT_CN_ALIAS \ + -keystore $CLIENT_STORE \ + -storepass $CLIENT_STORE_PWD \ + -noprompt +} + +while [ "$CLIENT_NUMBER" != "$client_finish" ]; do + CLIENT_CN_NAME=$(end_point) + CLIENT_CN_ALIAS=$(client_alias_point) + echo "$CLIENT_CN_NAME" + echo "$CLIENT_CN_ALIAS" + cert_end_point + CLIENT_NUMBER=$(($CLIENT_NUMBER + 1)) + echo "number $CLIENT_NUMBER" + echo "finish $client_finish" +done + +echo +echo "${H0}!!! Warning ${H2}Migrate ${H1}${SERVER_STORE} ${H2}to ${H1}PKCS12 ${H2}which is an industry standard format..${RESET}" +keytool \ + -importkeystore \ + -srckeystore $SERVER_STORE \ + -destkeystore $SERVER_STORE \ + -deststoretype pkcs12 \ + -srcstorepass $SERVER_STORE_PWD + +echo +echo "${H0}!!! Warning ${H2}Migrate ${H1}${CLIENT_STORE} ${H2}to ${H1}PKCS12 ${H2}which is an industry standard format..${RESET}" +keytool \ + -importkeystore \ + -srckeystore $CLIENT_STORE \ + -destkeystore $CLIENT_STORE \ + -deststoretype pkcs12 \ + -srcstorepass $CLIENT_STORE_PWD diff --git a/transport/lwm2m/src/main/data/credentials/shell/lwM2M_keygen.properties b/transport/lwm2m/src/main/data/credentials/shell/lwM2M_keygen.properties new file mode 100644 index 0000000000..18f851e4dd --- /dev/null +++ b/transport/lwm2m/src/main/data/credentials/shell/lwM2M_keygen.properties @@ -0,0 +1,57 @@ +# +# Copyright © 2016-2017 The Thingsboard Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# Keystore common parameters +ROOT_KEY_ALIAS=rootCA +DOMAIN_SUFFIX="$(hostname)" +ROOT_CN="$DOMAIN_SUFFIX $ROOT_KEY_ALIAS" +ORGANIZATIONAL_UNIT=Thingsboard +ORGANIZATION=Thingsboard +CITY=SF +STATE_OR_PROVINCE=CA +TWO_LETTER_COUNTRY_CODE=US +VALIDITY=36500 #days +STORETYPE="JKS" + +#Server +SERVER_STORE=serverKeyStore1.jks +SERVER_STORE_PWD=server_ks_password1 +SERVER_ALIAS=server1 +SERVER_CN="$DOMAIN_SUFFIX server LwM2M signed by root CA" +SERVER_SELF_ALIAS=server_self_signed +SERVER_SELF_CN="$DOMAIN_SUFFIX server LwM2M self-signed" +BOOTSTRAP_ALIAS=bootstrap1 +BOOTSTRAP_CN="$DOMAIN_SUFFIX bootstrap server LwM2M signed by root CA" +BOOTSTRAP_SELF_ALIAS=bootstrap_self_signed +BOOTSTRAP_SELF_CN="$DOMAIN_SUFFIX bootstrap server LwM2M self-signed" + +# Client +CLIENT_STORE=clientKeyStore1.jks +CLIENT_STORE_PWD=client_ks_password1 +CLIENT_ALIAS=client_alias_1 +CLIENT_PREFIX=LwX509_ +CLIENT_SELF_ALIAS=client_self_signed +CLIENT_SELF_CN="$DOMAIN_SUFFIX client LwM2M self-signed" + +# Color output stuff +red=`tput setaf 1` +green=`tput setaf 2` +blue=`tput setaf 4` +bold=`tput bold` +H0=${red}${bold} +H1=${green}${bold} +H2=${blue} +RESET=`tput sgr0` diff --git a/transport/lwm2m/src/main/data/models/LWM2M_Connectivity_Monitoring-v1_0_2.xml b/transport/lwm2m/src/main/data/models/LWM2M_Connectivity_Monitoring-v1_0_2.xml deleted file mode 100644 index 48e942983d..0000000000 --- a/transport/lwm2m/src/main/data/models/LWM2M_Connectivity_Monitoring-v1_0_2.xml +++ /dev/null @@ -1,167 +0,0 @@ - - - - - Connectivity Monitoring - - This LwM2M Object enables monitoring of parameters related to network connectivity. In this general connectivity Object, the Resources are limited to the most general cases common to most network bearers. It is recommended to read the description, which refers to relevant standard development organizations (e.g. 3GPP, IEEE). The goal of the Connectivity Monitoring Object is to carry information reflecting the more up to date values of the current connection for monitoring purposes. Resources such as Link Quality, Radio Signal Strength, Cell ID are retrieved during connected mode at least for cellular networks. - - 4 - urn:oma:lwm2m:oma:4 - 1.0 - 1.0 - Single - Optional - - - Network Bearer - R - Single - Mandatory - Integer - 0-50 - - - Indicates the network bearer used for the current LwM2M communication session from the network bearer list below. The number range is split into three categories: 0 - 20 are Cellular Bearers 21 - 40 are Wireless Bearers 41 - 50 are Wireline Bearers More specifically: 0: GSM cellular network 1: TD-SCDMA cellular network 2: WCDMA cellular network 3: CDMA2000 cellular network 4: WiMAX cellular network 5: LTE-TDD cellular network 6: LTE-FDD cellular network 7: NB-IoT 8 - 20: Reserved for other types of cellular network 21: WLAN network 22: Bluetooth network 23: IEEE 802.15.4 network 24 - 40: Reserved for other types of local wireless network 41: Ethernet 42: DSL 43: PLC 44 - 50: reserved for other types of wireline networks. - - - - Available Network Bearer - R - Multiple - Mandatory - Integer - 0-50 - - - Indicates a list of current available network bearer. Each Resource Instance has a value from the network bearer list. - - - - Radio Signal Strength - R - Single - Mandatory - Integer - - dBm - - Indicates the average value of the received signal strength indication used in the current network bearer (as indicated by Resource 0 of this Object). For the following network bearers the signal strength parameters indicated below are represented by this resource: GSM: RSSI UMTS: RSCP LTE: RSRP NB-IoT: NRSRP For more details on Network Measurement Report, refer to the appropriate Cellular or Wireless Network standards, (e.g. for LTE Cellular Network refer to 3GPP TS 36.133 specification). - - - - Link Quality - R - Single - Optional - Integer - - - - This contains received link quality e.g. LQI for IEEE 802.15.4 (range 0...255), RxQual Downlink for GSM (range 0...7, refer to [3GPP 44.018] for more details on Network Measurement Report encoding), RSRQ for LTE, (refer to [3GPP 36.214]), NRSRQ for NB-IoT (refer to [3GPP 36.214]). - - - - IP Addresses - R - Multiple - Mandatory - String - - - - The IP addresses assigned to the connectivity interface. (e.g. IPv4, IPv6, etc.) - - - - Router IP Addresses - R - Multiple - Optional - String - - - - The IP address of the next-hop IP router, on each of the interfaces specified in resource 4 (IP Addresses). Note: This IP Address doesn’t indicate the Server IP address. - - - - Link Utilization - R - Single - Optional - Integer - 0-100 - % - - The percentage indicating the average utilization of the link to the next-hop IP router. - - - - APN - R - Multiple - Optional - String - - - - Access Point Name in case Network Bearer Resource is a Cellular Network. - - - - Cell ID - R - Single - Optional - Integer - - - - Serving Cell ID in case Network Bearer Resource is a Cellular Network. As specified in TS [3GPP 23.003] and in [3GPP. 24.008]. Range (0...65535) in GSM/EDGE UTRAN Cell ID has a length of 28 bits. Cell Identity in WCDMA/TD-SCDMA. Range: (0...268435455). LTE Cell ID has a length of 28 bits. Parameter definitions in [3GPP 25.331]. - - - - SMNC - R - Single - Optional - Integer - 0-999 - % - - Serving Mobile Network Code. This is applicable when the Network Bearer Resource value is referring to a cellular network. As specified in TS [3GPP 23.003]. - - - - SMCC - R - Single - Optional - Integer - 0-999 - - - Serving Mobile Country Code. This is applicable when the Network Bearer Resource value is referring to a cellular network. As specified in TS [3GPP 23.003]. - - - - - - diff --git a/transport/lwm2m/src/main/data/models/LwM2M_BinaryAppDataContainer-v1_0_1.xml b/transport/lwm2m/src/main/data/models/LwM2M_BinaryAppDataContainer-v1_0_1.xml deleted file mode 100644 index 374dac72bc..0000000000 --- a/transport/lwm2m/src/main/data/models/LwM2M_BinaryAppDataContainer-v1_0_1.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - - - - BinaryAppDataContainer - - 19 - urn:oma:lwm2m:oma:19 - 1.0 - 1.0 - Multiple - Optional - - Data - RW - - - - Multiple - Mandatory - Opaque - - - - - Data Priority - RW - Single - Optional - Integer - 1 bytes - - - - Data Creation Time - RW - Single - Optional - Time - - - - - Data Description - RW - Single - Optional - String - 32 bytes - - - - Data Format - RW - Single - Optional - String - 32 bytes - - - - App ID - RW - Single - Optional - Integer - 2 bytes - - - - - - diff --git a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml index d6fe7b5b1f..f25dd2bb59 100644 --- a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml +++ b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml @@ -42,6 +42,7 @@ zk: # LWM2M server parameters transport: + # Local LwM2M transport parameters lwm2m: # Enable/disable lvm2m transport protocol. enabled: "${LWM2M_ENABLED:true}" @@ -51,7 +52,13 @@ transport: timeout: "${LWM2M_TIMEOUT:120000}" # model_path_file: "${LWM2M_MODEL_PATH_FILE:./common/transport/lwm2m/src/main/resources/models/}" model_path_file: "${LWM2M_MODEL_PATH_FILE:}" - support_deprecated_ciphers_enable: "${LWM2M_SUPPORT_DEPRECATED_CIPHERS_ENABLED:true}" + recommended_ciphers: "${LWM2M_RECOMMENDED_CIPHERS:false}" + recommended_supported_groups: "${LWM2M_RECOMMENDED_SUPPORTED_GROUPS:false}" + request_pool_size: "${LWM2M_REQUEST_POOL_SIZE:100}" + request_error_pool_size: "${LWM2M_REQUEST_ERROR_POOL_SIZE:10}" + registered_pool_size: "${LWM2M_REGISTERED_POOL_SIZE:10}" + update_registered_pool_size: "${LWM2M_UPDATE_REGISTERED_POOL_SIZE:10}" + un_registered_pool_size: "${LWM2M_UN_REGISTERED_POOL_SIZE:10}" secure: # Only Certificate_x509: # To get helps about files format and how to generate it, see: https://github.com/eclipse/leshan/wiki/Credential-files-format @@ -64,24 +71,19 @@ transport: root_alias: "${LWM2M_SERVER_ROOT_CA:rootca}" enable_gen_psk_rpk: "${ENABLE_GEN_PSK_RPK:true}" server: + id: "${LWM2M_SERVER_ID:123}" bind_address: "${LWM2M_BIND_ADDRESS:0.0.0.0}" - bind_port: "${LWM2M_BIND_PORT:5685}" - bind_port_cert: "${LWM2M_BIND_PORT_CERT:5687}" + bind_port_no_sec_psk: "${LWM2M_BIND_PORT_NO_SEC_PSK:5685}" + bind_port_no_sec_rpk: "${LWM2M_BIND_PORT_NO_SEC_RPK:5687}" + bind_port_no_sec_x509: "${LWM2M_BIND_PORT_NO_SEC_X509:5689}" secure: - start_all: "${START_SERVER_ALL:true}" - #leshan.core (V1_1) - #DTLS security modes: - #0: Pre-Shared Key mode - #1: Raw Public Key mode - #2: Certificate mode X509 - #3: NoSec mode * - #OMA-TS-LightweightM2M_Core-V1_1_1-20190617-A (add) - #4: Certificate mode X509 with EST - # If only startAll == false - dtls_mode: "${LWM2M_SECURITY_MODE:1}" bind_address: "${LWM2M_BIND_ADDRESS:0.0.0.0}" - bind_port: "${LWM2M_BIND_PORT_SEC:5686}" - bind_port_cert: "${LWM2M_BIND_PORT_SEC_CERT:5688}" + start_psk: "${START_SERVER_PSK:true}" + start_rpk: "${START_SERVER_RPK:true}" + start_x509: "${START_SERVER_X509:true}" + bind_port_psk: "${LWM2M_BIND_PORT_SEC_PSK:5686}" + bind_port_rpk: "${LWM2M_BIND_PORT_SEC_RPK:5688}" + bind_port_x509: "${LWM2M_BIND_PORT_SEC_X509:5690}" # Only RPK: Public & Private Key # create_rpk: "${CREATE_RPK:}" public_x: "${LWM2M_SERVER_PUBLIC_X:405354ea8893471d9296afbc8b020a5c6201b0bb25812a53b849d4480fa5f069}" @@ -91,16 +93,19 @@ transport: alias: "${LWM2M_KEYSTORE_ALIAS_SERVER:server}" bootstrap: enable: "${BOOTSTRAP:true}" + id: "${LWM2M_SERVER_ID:111}" bind_address: "${LWM2M_BIND_ADDRESS_BS:0.0.0.0}" - bind_port: "${LWM2M_BIND_PORT_BS:5689}" - bind_port_cert: "${LWM2M_BIND_PORT_SER_BS:5691}" + bind_port_no_sec_psk: "${LWM2M_BIND_PORT_NO_SEC_BS:5691}" + bind_port_no_sec_rpk: "${LWM2M_BIND_PORT_NO_SEC_BS:5693}" + bind_port_no_sec_x509: "${LWM2M_BIND_PORT_NO_SEC_BS:5695}" secure: - start_all: "${START_BOOTSTRAP_ALL:true}" - # If only startAll == false - dtls_mode: "${LWM2M_SECURITY_MODE_BS:1}" bind_address: "${LWM2M_BIND_ADDRESS_BS:0.0.0.0}" - bind_port: "${LWM2M_BIND_PORT_SEC_BS:5690}" - bind_port_cert: "${LWM2M_BIND_PORT_SEC_CERT_BS:5692}" + start_psk: "${START_SERVER_PSK_BS:true}" + start_rpk: "${START_SERVER_RPK_BS:true}" + start_x509: "${START_SERVER_X509_BS:true}" + bind_port_psk: "${LWM2M_BIND_PORT_SEC_PSK_BS:5692}" + bind_port_rpk: "${LWM2M_BIND_PORT_SER_RPK_BS:5694}" + bind_port_x509: "${LWM2M_BIND_PORT_SEC_X509_BS:5696}" # Only RPK: Public & Private Key public_x: "${LWM2M_SERVER_PUBLIC_X_BS:993ef2b698c6a9c0c1d8be78b13a9383c0854c7c7c7a504d289b403794648183}" public_y: "${LWM2M_SERVER_PUBLIC_Y_BS:267412d5fc4e5ceb2257cb7fd7f76ebdac2fa9aa100afb162e990074cc0bfaa2}" diff --git a/ui-ngx/angular.json b/ui-ngx/angular.json index 3cad30304a..3cc2d92d57 100644 --- a/ui-ngx/angular.json +++ b/ui-ngx/angular.json @@ -247,6 +247,7 @@ }, "defaultProject": "thingsboard", "cli": { - "packageManager": "yarn" + "packageManager": "yarn", + "analytics": false } -} +} \ No newline at end of file diff --git a/ui-ngx/src/app/core/http/device-profile.service.ts b/ui-ngx/src/app/core/http/device-profile.service.ts index 16f6edb512..26c642c4bc 100644 --- a/ui-ngx/src/app/core/http/device-profile.service.ts +++ b/ui-ngx/src/app/core/http/device-profile.service.ts @@ -21,10 +21,9 @@ import { defaultHttpOptionsFromConfig, RequestConfig } from './http-utils'; import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { DeviceProfile, DeviceProfileInfo, DeviceTransportType } from '@shared/models/device.models'; -import { isDefinedAndNotNull } from '@core/utils'; -import { - ObjectLwM2M, ServerSecurityConfig -} from "../../modules/home/components/profile/device/lwm2m/profile-config.models"; +import { isDefinedAndNotNull, isEmptyStr } from '@core/utils'; +import { ObjectLwM2M, ServerSecurityConfig } from '@home/components/profile/device/lwm2m/profile-config.models'; +import { SortOrder } from '@shared/models/page/sort-order'; @Injectable({ providedIn: 'root' @@ -33,7 +32,8 @@ export class DeviceProfileService { constructor( private http: HttpClient - ) { } + ) { + } public getDeviceProfiles(pageLink: PageLink, config?: RequestConfig): Observable> { return this.http.get>(`/api/deviceProfiles${pageLink.toQuery()}`, defaultHttpOptionsFromConfig(config)); @@ -43,16 +43,31 @@ export class DeviceProfileService { return this.http.get(`/api/deviceProfile/${deviceProfileId}`, defaultHttpOptionsFromConfig(config)); } - public getLwm2mObjects(objectIds: number [], config?: RequestConfig): Observable { - return this.http.get(`/api/lwm2m/deviceProfile/${objectIds}`, defaultHttpOptionsFromConfig(config)); + public getLwm2mObjects(sortOrder: SortOrder, objectIds?: number[], searchText?: string, config?: RequestConfig): + Observable> { + let url = `/api/lwm2m/deviceProfile/?sortProperty=${sortOrder.property}&sortOrder=${sortOrder.direction}`; + if (isDefinedAndNotNull(objectIds) && objectIds.length > 0) { + url += `&objectIds=${objectIds}`; + } + if (isDefinedAndNotNull(searchText) && !isEmptyStr(searchText)) { + url += `&searchText=${searchText}`; + } + return this.http.get>(url, defaultHttpOptionsFromConfig(config)); } - public getLwm2mBootstrapSecurityInfo(securityMode: string, bootstrapServerIs: boolean, config?: RequestConfig): Observable { - return this.http.get(`/api/lwm2m/deviceProfile/bootstrap/${securityMode}/${bootstrapServerIs}`, defaultHttpOptionsFromConfig(config)); + public getLwm2mBootstrapSecurityInfo(securityMode: string, bootstrapServerIs: boolean, + config?: RequestConfig): Observable { + return this.http.get( + `/api/lwm2m/deviceProfile/bootstrap/${securityMode}/${bootstrapServerIs}`, + defaultHttpOptionsFromConfig(config) + ); } public getLwm2mObjectsPage(pageLink: PageLink, config?: RequestConfig): Observable> { - return this.http.get>(`/api/lwm2m/deviceProfile/objects${pageLink.toQuery()}`, defaultHttpOptionsFromConfig(config)); + return this.http.get>( + `/api/lwm2m/deviceProfile/objects${pageLink.toQuery()}`, + defaultHttpOptionsFromConfig(config) + ); } public saveDeviceProfile(deviceProfile: DeviceProfile, config?: RequestConfig): Observable { diff --git a/ui-ngx/src/app/modules/home/components/device/device-credentials.component.html b/ui-ngx/src/app/modules/home/components/device/device-credentials.component.html index 44337d30a5..9243feb18a 100644 --- a/ui-ngx/src/app/modules/home/components/device/device-credentials.component.html +++ b/ui-ngx/src/app/modules/home/components/device/device-credentials.component.html @@ -90,9 +90,8 @@
diff --git a/ui-ngx/src/app/modules/home/components/device/device-credentials.component.ts b/ui-ngx/src/app/modules/home/components/device/device-credentials.component.ts index 4c622747ef..b6eb364b2f 100644 --- a/ui-ngx/src/app/modules/home/components/device/device-credentials.component.ts +++ b/ui-ngx/src/app/modules/home/components/device/device-credentials.component.ts @@ -14,7 +14,7 @@ /// limitations under the License. /// -import { Component, forwardRef, Inject, Input, OnDestroy, OnInit } from '@angular/core'; +import { Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core'; import { ControlValueAccessor, FormBuilder, @@ -41,8 +41,7 @@ import { DeviceCredentialsDialogLwm2mData, END_POINT, getDefaultSecurityConfig, - JSON_ALL_CONFIG, - SecurityConfigModels + JSON_ALL_CONFIG } from '@home/pages/device/lwm2m/security-config.models'; import { TranslateService } from '@ngx-translate/core'; import { MatDialog } from '@angular/material/dialog'; @@ -197,6 +196,7 @@ export class DeviceCredentialsComponent implements ControlValueAccessor, OnInit, this.deviceCredentialsFormGroup.get('credentialsBasic').disable({emitEvent: false}); break; case DeviceCredentialsType.X509_CERTIFICATE: + case DeviceCredentialsType.LWM2M_CREDENTIALS: this.deviceCredentialsFormGroup.get('credentialsValue').setValidators([Validators.required]); this.deviceCredentialsFormGroup.get('credentialsValue').updateValueAndValidity({emitEvent: false}); this.deviceCredentialsFormGroup.get('credentialsId').setValidators([]); @@ -211,13 +211,6 @@ export class DeviceCredentialsComponent implements ControlValueAccessor, OnInit, this.deviceCredentialsFormGroup.get('credentialsValue').setValidators([]); this.deviceCredentialsFormGroup.get('credentialsValue').updateValueAndValidity({emitEvent: false}); 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) { $event.stopPropagation(); $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, { disableClose: true, panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], data: { - jsonAllConfig: (value === null || value.length === 0) ? getDefaultSecurityConfig() as SecurityConfigModels : JSON.parse(value) as SecurityConfigModels, - endPoint: (id === null) ? DEFAULT_END_POINT : id, - isNew: (id === null || value === null || value.length === 0) + jsonAllConfig: credentialsValue, + endPoint: credentialsId } }).afterClosed().subscribe( (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.get('credentialsId').patchValue((Object.keys(res[END_POINT]).length === 0 || JSON.stringify(res[END_POINT]) === "[{}]") ? null : JSON.stringify(res[END_POINT]).split('\"').join('')); + this.deviceCredentialsFormGroup.patchValue({ + 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(); } } ); } + + private isDefautLw2mResponse(response: object): boolean { + return Object.keys(response).length === 0 || JSON.stringify(response) === '[{}]'; + } } diff --git a/ui-ngx/src/app/modules/home/components/home-components.module.ts b/ui-ngx/src/app/modules/home/components/home-components.module.ts index 67f86cb812..876d7fe785 100644 --- a/ui-ngx/src/app/modules/home/components/home-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/home-components.module.ts @@ -307,7 +307,6 @@ import { Lwm2mProfileComponentsModule } from '@home/components/profile/device/lw EditAlarmDetailsDialogComponent, DeviceProfileProvisionConfigurationComponent, AlarmScheduleComponent, - Lwm2mProfileComponentsModule, SmsProviderConfigurationComponent, AwsSnsProviderConfigurationComponent, TwilioSmsProviderConfigurationComponent diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.html b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.html index 0e10a8e843..f0fe7d8dcd 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.html @@ -21,10 +21,9 @@
{{ 'device-profile.lwm2m.mode' | translate }} - + + [value]="securityMode"> {{ credentialTypeLwM2MNamesMap.get(securityConfigLwM2MType[securityMode]) }} @@ -87,33 +86,40 @@ {{ 'device-profile.lwm2m.bootstrap-server' | translate }}
-
-
- - {{ 'device-profile.lwm2m.server-public-key' | translate }} - - {{serverPublicKey.value?.length || 0}}/{{lenMaxServerPublicKey}} - - {{ 'device-profile.lwm2m.server-public-key' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} - - - {{ 'device-profile.lwm2m.client-key' | translate }} - {{ 'device-profile.lwm2m.pattern_hex_dec_182' | translate }} - - - {{ 'device-profile.lwm2m.client-key' | translate }} - {{ 'device-profile.lwm2m.pattern_hex_dec' | translate }} - - -
+
+ + {{ 'device-profile.lwm2m.server-public-key' | translate }} + + {{serverPublicKey.value?.length || 0}}/{{lenMaxServerPublicKey}} + + {{ 'device-profile.lwm2m.server-public-key' | translate }} + {{ 'device-profile.lwm2m.required' | translate }} + + + {{ 'device-profile.lwm2m.server-public-key' | translate }} + {{ translate.get('device-profile.lwm2m.pattern_hex_dec', { + count: 0}) | async }} + + + {{ 'device-profile.lwm2m.server-public-key' | translate }} + {{ translate.get('device-profile.lwm2m.pattern_hex_dec', { + count: lenMaxServerPublicKey }) | async }} + +
diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.ts b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.ts index 9f1fed9bc9..fc766683f2 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.ts @@ -14,36 +14,31 @@ /// limitations under the License. /// -import { Component, forwardRef, Inject, Input, OnInit } from "@angular/core"; - -import { - ControlValueAccessor, - FormBuilder, FormGroup, NG_VALUE_ACCESSOR, NgModel, Validators -} from "@angular/forms"; +import { Component, forwardRef, Inject, Input } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; import { - SECURITY_CONFIG_MODE, - SECURITY_CONFIG_MODE_NAMES, - KEY_PUBLIC_REGEXP_PSK, - ServerSecurityConfig, - LEN_MAX_PUBLIC_KEY_PSK, - LEN_MAX_PUBLIC_KEY_RPK_X509, - KEY_PUBLIC_REGEXP_X509, + DEFAULT_CLIENT_HOLD_OFF_TIME, + DEFAULT_ID_SERVER, DEFAULT_PORT_BOOTSTRAP_NO_SEC, DEFAULT_PORT_SERVER_NO_SEC, - DEFAULT_CLIENT_HOLD_OFF_TIME, - DEFAULT_ID_SERVER -} from "./profile-config.models"; -import { Store } from "@ngrx/store"; -import { AppState } from "@core/core.state"; -import { coerceBooleanProperty } from "@angular/cdk/coercion"; -import { WINDOW } from "../../../../../../core/services/window.service"; + KEY_REGEXP_HEX_DEC, + LEN_MAX_PUBLIC_KEY_RPK, + LEN_MAX_PUBLIC_KEY_X509, + SECURITY_CONFIG_MODE, + SECURITY_CONFIG_MODE_NAMES, + ServerSecurityConfig +} from './profile-config.models'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; +import { WINDOW } from '@core/services/window.service'; import { pairwise, startWith } from 'rxjs/operators'; import { DeviceProfileService } from '@core/http/device-profile.service'; +import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'tb-profile-lwm2m-device-config-server', templateUrl: './lwm2m-device-config-server.component.html', - styleUrls: [], providers: [ { provide: NG_VALUE_ACCESSOR, @@ -53,15 +48,17 @@ import { DeviceProfileService } from '@core/http/device-profile.service'; ] }) -export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAccessor, Validators { +export class Lwm2mDeviceConfigServerComponent implements ControlValueAccessor { - valuePrev = null as any; private requiredValue: boolean; + + valuePrev = null; serverFormGroup: FormGroup; securityConfigLwM2MType = SECURITY_CONFIG_MODE; securityConfigLwM2MTypes = Object.keys(SECURITY_CONFIG_MODE); credentialTypeLwM2MNamesMap = SECURITY_CONFIG_MODE_NAMES; - lenMaxServerPublicKey = LEN_MAX_PUBLIC_KEY_PSK; + lenMinServerPublicKey = 0; + lenMaxServerPublicKey = LEN_MAX_PUBLIC_KEY_RPK; currentSecurityMode = null; @@ -69,7 +66,7 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc disabled: boolean; @Input() - bootstrapServerIs: boolean + bootstrapServerIs: boolean; get required(): boolean { return this.requiredValue; @@ -81,10 +78,11 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc } constructor(protected store: Store, + public translate: TranslateService, public fb: FormBuilder, private deviceProfileService: DeviceProfileService, @Inject(WINDOW) private window: Window) { - this.serverFormGroup = this.getServerGroup(); + this.serverFormGroup = this.initServerGroup(); this.serverFormGroup.get('securityMode').valueChanges.pipe( startWith(null), pairwise() @@ -103,49 +101,45 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc }); } - ngOnInit(): void { - } - - updateValueFields(serverData: ServerSecurityConfig): void { - serverData['bootstrapServerIs'] = this.bootstrapServerIs; + private updateValueFields = (serverData: ServerSecurityConfig): void => { + serverData.bootstrapServerIs = this.bootstrapServerIs; this.serverFormGroup.patchValue(serverData, {emitEvent: false}); this.serverFormGroup.get('bootstrapServerIs').disable(); const securityMode = this.serverFormGroup.get('securityMode').value as SECURITY_CONFIG_MODE; this.updateValidate(securityMode); } - updateValidate(securityMode: SECURITY_CONFIG_MODE): void { + private updateValidate = (securityMode: SECURITY_CONFIG_MODE): void => { switch (securityMode) { case SECURITY_CONFIG_MODE.NO_SEC: - this.serverFormGroup.get('serverPublicKey').setValidators([]); + this.setValidatorsNoSecPsk(); break; case SECURITY_CONFIG_MODE.PSK: - this.lenMaxServerPublicKey = LEN_MAX_PUBLIC_KEY_PSK; - this.serverFormGroup.get('serverPublicKey').setValidators([]); + this.setValidatorsNoSecPsk(); break; case SECURITY_CONFIG_MODE.RPK: - this.lenMaxServerPublicKey = LEN_MAX_PUBLIC_KEY_RPK_X509; - this.serverFormGroup.get('serverPublicKey').setValidators([Validators.required, Validators.pattern(KEY_PUBLIC_REGEXP_PSK)]); + this.lenMinServerPublicKey = LEN_MAX_PUBLIC_KEY_RPK; + this.lenMaxServerPublicKey = LEN_MAX_PUBLIC_KEY_RPK; + this.setValidatorsRpkX509(); break; case SECURITY_CONFIG_MODE.X509: - this.lenMaxServerPublicKey = LEN_MAX_PUBLIC_KEY_RPK_X509; - this.serverFormGroup.get('serverPublicKey').setValidators([Validators.required, Validators.pattern(KEY_PUBLIC_REGEXP_X509)]); + this.lenMinServerPublicKey = 0; + this.lenMaxServerPublicKey = LEN_MAX_PUBLIC_KEY_X509; + this.setValidatorsRpkX509(); break; } - this.checkValueWithNewValidate(); + this.serverFormGroup.updateValueAndValidity(); } - checkValueWithNewValidate(): void { - this.serverFormGroup.patchValue({ - host: this.serverFormGroup.get('host').value, - port: this.serverFormGroup.get('port').value, - bootstrapServerIs: this.serverFormGroup.get('bootstrapServerIs').value, - serverPublicKey: this.serverFormGroup.get('serverPublicKey').value, - clientHoldOffTime: this.serverFormGroup.get('clientHoldOffTime').value, - serverId: this.serverFormGroup.get('serverId').value, - bootstrapServerAccountTimeout: this.serverFormGroup.get('bootstrapServerAccountTimeout').value, - }, - {emitEvent: true}); + private setValidatorsNoSecPsk = (): void => { + this.serverFormGroup.get('serverPublicKey').setValidators([]); + } + + private setValidatorsRpkX509 = (): void => { + this.serverFormGroup.get('serverPublicKey').setValidators([Validators.required, + Validators.pattern(KEY_REGEXP_HEX_DEC), + Validators.minLength(this.lenMinServerPublicKey), + Validators.maxLength(this.lenMaxServerPublicKey)]); } writeValue(value: any): void { @@ -154,18 +148,17 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc } } - private propagateChange = (v: any) => { - }; + private propagateChange = (v: any) => {}; registerOnChange(fn: any): void { this.propagateChange = fn; } - private propagateChangeState(value: any): void { + private propagateChangeState = (value: any): void => { if (value !== undefined) { if (this.valuePrev === null) { - this.valuePrev = "init"; - } else if (this.valuePrev === "init") { + this.valuePrev = 'init'; + } else if (this.valuePrev === 'init') { this.valuePrev = value; } else if (JSON.stringify(value) !== JSON.stringify(this.valuePrev)) { this.valuePrev = value; @@ -191,21 +184,21 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc registerOnTouched(fn: any): void { } - getServerGroup(): FormGroup { - const port = (this.bootstrapServerIs) ? DEFAULT_PORT_BOOTSTRAP_NO_SEC : DEFAULT_PORT_SERVER_NO_SEC; + private initServerGroup = (): FormGroup => { + const port = this.bootstrapServerIs ? DEFAULT_PORT_BOOTSTRAP_NO_SEC : DEFAULT_PORT_SERVER_NO_SEC; return this.fb.group({ - host: [this.window.location.hostname, this.required ? [Validators.required] : []], - port: [port, this.required ? [Validators.required] : []], - bootstrapServerIs: [this.bootstrapServerIs, []], - securityMode: [this.fb.control(SECURITY_CONFIG_MODE.NO_SEC), []], - serverPublicKey: ['', this.required ? [Validators.required] : []], - clientHoldOffTime: [DEFAULT_CLIENT_HOLD_OFF_TIME, this.required ? [Validators.required] : []], - serverId: [DEFAULT_ID_SERVER, this.required ? [Validators.required] : []], - bootstrapServerAccountTimeout: ['', this.required ? [Validators.required] : []], - }) + host: [this.window.location.hostname, this.required ? Validators.required : ''], + port: [port, this.required ? Validators.required : ''], + bootstrapServerIs: [this.bootstrapServerIs, ''], + securityMode: [this.fb.control(SECURITY_CONFIG_MODE.NO_SEC)], + serverPublicKey: ['', this.required ? Validators.required : ''], + clientHoldOffTime: [DEFAULT_CLIENT_HOLD_OFF_TIME, this.required ? Validators.required : ''], + serverId: [DEFAULT_ID_SERVER, this.required ? Validators.required : ''], + bootstrapServerAccountTimeout: ['', this.required ? Validators.required : ''], + }); } - getLwm2mBootstrapSecurityInfo(mode: string) { + private getLwm2mBootstrapSecurityInfo = (mode: string): void => { this.deviceProfileService.getLwm2mBootstrapSecurityInfo(mode, this.serverFormGroup.get('bootstrapServerIs').value).subscribe( (serverSecurityConfig) => { this.serverFormGroup.patchValue({ diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.html b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.html index 846f991e3e..57b767fb07 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.html @@ -15,126 +15,140 @@ limitations under the License. --> -
-
- - -
- - -
-
- - -
-
- -
- - - - -
{{ 'device-profile.lwm2m.servers' | translate | uppercase }}
-
-
-
-
- - {{ 'device-profile.lwm2m.short-id' | translate }} - - - {{ 'device-profile.lwm2m.short-id' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} - - - - {{ 'device-profile.lwm2m.lifetime' | translate }} - - - {{ 'device-profile.lwm2m.lifetime' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} - - -
-
- - {{ 'device-profile.lwm2m.default-min-period' | translate }} - - - {{ 'device-profile.lwm2m.default-min-period' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} - - - - {{ 'device-profile.lwm2m.binding' | translate }} - - - {{ 'device-profile.lwm2m.binding' | translate }} - {{ 'device-profile.lwm2m.required' | translate }} - - -
-
- - {{ 'device-profile.lwm2m.notif-if-disabled' | translate }} - -
-
-
-
- - - - -
{{ 'device-profile.lwm2m.bootstrap-server' | translate | uppercase }}
-
-
-
- - -
-
-
- - - - -
{{ 'device-profile.lwm2m.lwm2m-server' | translate | uppercase }}
-
-
-
- - -
-
-
-
-
- -
+
+ + + +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+ + + + +
{{ 'device-profile.lwm2m.servers' | translate | uppercase }}
+
+
+ +
+
+ + {{ 'device-profile.lwm2m.short-id' | translate }} + + + {{ 'device-profile.lwm2m.short-id' | translate }} + {{ 'device-profile.lwm2m.required' | translate }} + + + + {{ 'device-profile.lwm2m.lifetime' | translate }} + + + {{ 'device-profile.lwm2m.lifetime' | translate }} + {{ 'device-profile.lwm2m.required' | translate }} + + +
+
+ + {{ 'device-profile.lwm2m.default-min-period' | translate }} + + + {{ 'device-profile.lwm2m.default-min-period' | translate }} + {{ 'device-profile.lwm2m.required' | translate }} + + + + {{ 'device-profile.lwm2m.binding' | translate }} + + + {{ 'device-profile.lwm2m.binding' | translate }} + {{ 'device-profile.lwm2m.required' | translate }} + + +
+
+ + {{ 'device-profile.lwm2m.notif-if-disabled' | translate }} + +
+
+
+
+
+ + + + +
{{ 'device-profile.lwm2m.bootstrap-server' | translate | uppercase }}
+
+
+ +
+ + +
+
+
+
+ + + + +
{{ 'device-profile.lwm2m.lwm2m-server' | translate | uppercase }}
+
+
+ +
+ + +
+
+
+
+
+
+
+
+ + +
-
-
-
-
-
+ + + + + diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.ts b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.ts index d724a25332..6451bbb0b8 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.ts @@ -14,58 +14,56 @@ /// limitations under the License. /// -import { - DeviceProfileTransportConfiguration, - DeviceTransportType -} from '@shared/models/device.models'; -import { - Component, - forwardRef, Inject, - Input, - OnInit -} from '@angular/core'; +import { DeviceProfileTransportConfiguration, DeviceTransportType } from '@shared/models/device.models'; +import { Component, forwardRef, Inject, Input } from '@angular/core'; import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; import { Store } from '@ngrx/store'; import { AppState } from '@app/core/core.state'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { ATTR, + getDefaultProfileConfig, + Instance, + KEY_NAME, + ObjectLwM2M, OBSERVE, OBSERVE_ATTR, - TELEMETRY, - ObjectLwM2M, getDefaultProfileConfig, KEY_NAME, Instance -} from "./profile-config.models"; -import { DeviceProfileService } from "../../../../../../core/http/device-profile.service"; -import { deepClone, isUndefined } from "../../../../../../core/utils"; -import { WINDOW } from "../../../../../../core/services/window.service"; + ProfileConfigModels, + ResourceLwM2M, + TELEMETRY +} from './profile-config.models'; +import { DeviceProfileService } from '@core/http/device-profile.service'; +import { deepClone, isDefinedAndNotNull, isUndefined } from '@core/utils'; +import { WINDOW } from '@core/services/window.service'; import { JsonObject } from '@angular/compiler-cli/ngcc/src/packages/entry_point'; -import { isNotNullOrUndefined } from 'codelyzer/util/isNotNullOrUndefined'; +import { Direction } from '@shared/models/page/sort-order'; @Component({ selector: 'tb-profile-lwm2m-device-transport-configuration', templateUrl: './lwm2m-device-profile-transport-configuration.component.html', - styleUrls: [], providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => Lwm2mDeviceProfileTransportConfigurationComponent), multi: true }] }) -export class Lwm2mDeviceProfileTransportConfigurationComponent implements ControlValueAccessor, OnInit, Validators { - - lwm2mDeviceProfileTransportConfFormGroup: FormGroup; - observeAttr = OBSERVE_ATTR as string; - observe = OBSERVE as string; - attribute = ATTR as string; - telemetry = TELEMETRY as string; - keyName = KEY_NAME as string; +export class Lwm2mDeviceProfileTransportConfigurationComponent implements ControlValueAccessor, Validators { + + private configurationValue: ProfileConfigModels; + private requiredValue: boolean; + private disabled = false; + + lwm2mDeviceProfileFormGroup: FormGroup; + lwm2mDeviceConfigFormGroup: FormGroup; + observeAttr = OBSERVE_ATTR; + observe = OBSERVE; + attribute = ATTR; + telemetry = TELEMETRY; + keyName = KEY_NAME; bootstrapServers: string; bootstrapServer: string; lwm2mServer: string; - private configurationValue: {}; - private requiredValue: boolean; - private disabled = false as boolean; - sortFunction = this.sortObjectKeyPathJson; + sortFunction: (key: string, value: object) => object; get required(): boolean { return this.requiredValue; @@ -77,29 +75,33 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro } private propagateChange = (v: any) => { - }; + } constructor(private store: Store, private fb: FormBuilder, private deviceProfileService: DeviceProfileService, @Inject(WINDOW) private window: Window) { - this.lwm2mDeviceProfileTransportConfFormGroup = this.fb.group({ - objectIds: [{}, Validators.required], - observeAttrTelemetry: [{'clientLwM2M': [] as ObjectLwM2M []}, Validators.required], + this.lwm2mDeviceProfileFormGroup = this.fb.group({ + objectIds: [null, Validators.required], + observeAttrTelemetry: [null, Validators.required], shortId: [null, Validators.required], lifetime: [null, Validators.required], defaultMinPeriod: [null, Validators.required], notifIfDisabled: [true, []], - binding: ["U", Validators.required], + binding: ['U', Validators.required], bootstrapServer: [null, Validators.required], lwm2mServer: [null, Validators.required], - configurationJson: [null, Validators.required], }); - this.lwm2mDeviceProfileTransportConfFormGroup.valueChanges.subscribe(value => { - if (!this.disabled) { - this.updateModel(); - } + this.lwm2mDeviceConfigFormGroup = this.fb.group({ + configurationJson: [null, Validators.required] + }); + this.lwm2mDeviceProfileFormGroup.valueChanges.subscribe((value) => { + this.updateDeviceProfileValue(value); + }); + this.lwm2mDeviceConfigFormGroup.valueChanges.subscribe(() => { + this.updateModel(); }); + this.sortFunction = this.sortObjectKeyPathJson; } registerOnChange(fn: any): void { @@ -109,33 +111,34 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro registerOnTouched(fn: any): void { } - ngOnInit() { - } - setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; if (isDisabled) { - this.lwm2mDeviceProfileTransportConfFormGroup.disable({emitEvent: false}); + this.lwm2mDeviceProfileFormGroup.disable({emitEvent: false}); + this.lwm2mDeviceConfigFormGroup.disable({emitEvent: false}); } else { - this.lwm2mDeviceProfileTransportConfFormGroup.enable({emitEvent: false}); + this.lwm2mDeviceProfileFormGroup.enable({emitEvent: false}); + this.lwm2mDeviceConfigFormGroup.enable({emitEvent: false}); } } writeValue(value: any | null): void { - value = (Object.keys(value).length == 0) ? getDefaultProfileConfig() : value; - this.lwm2mDeviceProfileTransportConfFormGroup.patchValue({ - configurationJson: value - }, - {emitEvent: false}); - this.configurationValue = this.lwm2mDeviceProfileTransportConfFormGroup.getRawValue().configurationJson; + this.configurationValue = (Object.keys(value).length === 0) ? getDefaultProfileConfig() : value; + this.lwm2mDeviceConfigFormGroup.patchValue({ + configurationJson: this.configurationValue + }, {emitEvent: false}); this.initWriteValue(); } - private initWriteValue(): void { - let modelValue = {"objectIds": null, "objectsList": []}; + private initWriteValue = (): void => { + const modelValue = {objectIds: null, objectsList: []}; modelValue.objectIds = this.getObjectsFromJsonAllConfig(); if (modelValue.objectIds !== null) { - this.deviceProfileService.getLwm2mObjects(modelValue.objectIds).subscribe( + const sortOrder = { + property: 'id', + direction: Direction.ASC + }; + this.deviceProfileService.getLwm2mObjects(sortOrder, modelValue.objectIds, null).subscribe( (objectsList) => { modelValue.objectsList = objectsList; this.updateWriteValue(modelValue); @@ -146,240 +149,176 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro } } - private updateWriteValue(value: any): void { - let objectsList = deepClone(value.objectsList); - this.lwm2mDeviceProfileTransportConfFormGroup.patchValue({ + private updateWriteValue = (value: any): void => { + const objectsList = value.objectsList; + this.lwm2mDeviceProfileFormGroup.patchValue({ objectIds: value, - observeAttrTelemetry: {clientLwM2M: this.getObserveAttrTelemetryObjects(objectsList)}, - shortId: this.configurationValue['bootstrap'].servers.shortId, - lifetime: this.configurationValue['bootstrap'].servers.lifetime, - defaultMinPeriod: this.configurationValue['bootstrap'].servers.defaultMinPeriod, - notifIfDisabled: this.configurationValue['bootstrap'].servers.notifIfDisabled, - binding: this.configurationValue['bootstrap'].servers.binding, - bootstrapServer: this.configurationValue['bootstrap'].bootstrapServer, - lwm2mServer: this.configurationValue['bootstrap'].lwm2mServer + observeAttrTelemetry: this.getObserveAttrTelemetryObjects(objectsList), + shortId: this.configurationValue.bootstrap.servers.shortId, + lifetime: this.configurationValue.bootstrap.servers.lifetime, + defaultMinPeriod: this.configurationValue.bootstrap.servers.defaultMinPeriod, + notifIfDisabled: this.configurationValue.bootstrap.servers.notifIfDisabled, + binding: this.configurationValue.bootstrap.servers.binding, + bootstrapServer: this.configurationValue.bootstrap.bootstrapServer, + lwm2mServer: this.configurationValue.bootstrap.lwm2mServer }, {emitEvent: false}); } - private updateModel() { + private updateModel = (): void => { let configuration: DeviceProfileTransportConfiguration = null; - if (this.lwm2mDeviceProfileTransportConfFormGroup.valid) { - this.upDateValueToJson(); - configuration = this.lwm2mDeviceProfileTransportConfFormGroup.getRawValue().configurationJson; + if (this.lwm2mDeviceConfigFormGroup.valid && this.lwm2mDeviceProfileFormGroup.valid) { + configuration = this.lwm2mDeviceConfigFormGroup.value.configurationJson; configuration.type = DeviceTransportType.LWM2M; } this.propagateChange(configuration); } - private updateObserveAttrTelemetryObjectFormGroup(objectsList: ObjectLwM2M[]) { - this.lwm2mDeviceProfileTransportConfFormGroup.patchValue({ - observeAttrTelemetry: {clientLwM2M: this.getObserveAttrTelemetryObjects(objectsList)} + private updateObserveAttrTelemetryObjectFormGroup = (objectsList: ObjectLwM2M[]): void => { + this.lwm2mDeviceProfileFormGroup.patchValue({ + observeAttrTelemetry: this.getObserveAttrTelemetryObjects(objectsList) }, {emitEvent: false}); - this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").markAsPristine({ - onlySelf: true - }); } - upDateValueToJson(): void { - this.upDateValueToJsonTab_0(); - this.upDateValueToJsonTab_1(); - } - - upDateValueToJsonTab_0(): void { - if (!this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").pristine) { - this.upDateObserveAttrTelemetryFromGroupToJson(this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").value['clientLwM2M']); - this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").markAsPristine({ - onlySelf: true - }); - this.upDateJsonAllConfig(); - } - } - - upDateValueToJsonTab_1(): void { - this.upDateValueServersToJson(); - if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('bootstrapServer').pristine) { - this.configurationValue['bootstrap'].bootstrapServer = this.lwm2mDeviceProfileTransportConfFormGroup.get('bootstrapServer').value; - this.lwm2mDeviceProfileTransportConfFormGroup.get('bootstrapServer').markAsPristine({ - onlySelf: true - }); - this.upDateJsonAllConfig(); - } - if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('lwm2mServer').pristine) { - this.configurationValue['bootstrap'].lwm2mServer = this.lwm2mDeviceProfileTransportConfFormGroup.get('lwm2mServer').value; - this.lwm2mDeviceProfileTransportConfFormGroup.get('lwm2mServer').markAsPristine({ - onlySelf: true - }); - this.upDateJsonAllConfig(); - } - } - - upDateValueServersToJson(): void { - if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('shortId').pristine) { - this.configurationValue['bootstrap'].servers.shortId = this.lwm2mDeviceProfileTransportConfFormGroup.get('shortId').value; - this.lwm2mDeviceProfileTransportConfFormGroup.get('shortId').markAsPristine({ - onlySelf: true - }); - this.upDateJsonAllConfig(); - } - if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('lifetime').pristine) { - this.configurationValue['bootstrap'].servers.lifetime = this.lwm2mDeviceProfileTransportConfFormGroup.get('lifetime').value; - this.lwm2mDeviceProfileTransportConfFormGroup.get('lifetime').markAsPristine({ - onlySelf: true - }); - this.upDateJsonAllConfig(); - } - if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('defaultMinPeriod').pristine) { - this.configurationValue['bootstrap'].servers.defaultMinPeriod = this.lwm2mDeviceProfileTransportConfFormGroup.get('defaultMinPeriod').value; - this.lwm2mDeviceProfileTransportConfFormGroup.get('defaultMinPeriod').markAsPristine({ - onlySelf: true - }); - this.upDateJsonAllConfig(); - } - if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('notifIfDisabled').pristine) { - this.configurationValue['bootstrap'].servers.notifIfDisabled = this.lwm2mDeviceProfileTransportConfFormGroup.get('notifIfDisabled').value; - this.lwm2mDeviceProfileTransportConfFormGroup.get('notifIfDisabled').markAsPristine({ - onlySelf: true - }); - this.upDateJsonAllConfig(); - } - if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('binding').pristine) { - this.configurationValue['bootstrap'].servers.binding = this.lwm2mDeviceProfileTransportConfFormGroup.get('binding').value; - this.lwm2mDeviceProfileTransportConfFormGroup.get('binding').markAsPristine({ - onlySelf: true - }); + private updateDeviceProfileValue(config): void { + if (this.lwm2mDeviceProfileFormGroup.valid) { + this.updateObserveAttrTelemetryFromGroupToJson(config.observeAttrTelemetry.clientLwM2M); + this.configurationValue.bootstrap.bootstrapServer = config.bootstrapServer; + this.configurationValue.bootstrap.lwm2mServer = config.lwm2mServer; + const bootstrapServers = this.configurationValue.bootstrap.servers; + bootstrapServers.shortId = config.shortId; + bootstrapServers.lifetime = config.lifetime; + bootstrapServers.defaultMinPeriod = config.defaultMinPeriod; + bootstrapServers.notifIfDisabled = config.notifIfDisabled; + bootstrapServers.binding = config.binding; this.upDateJsonAllConfig(); + this.updateModel(); } } - getObserveAttrTelemetryObjects(listObject: ObjectLwM2M[]): ObjectLwM2M [] { - let clientObserveAttr = deepClone(listObject) as ObjectLwM2M[]; + private getObserveAttrTelemetryObjects = (listObject: ObjectLwM2M[]): object => { + const clientObserveAttrTelemetry = listObject; if (this.configurationValue[this.observeAttr]) { - let observeArray = this.configurationValue[this.observeAttr][this.observe] as Array; - let attributeArray = this.configurationValue[this.observeAttr][this.attribute] as Array; - let telemetryArray = this.configurationValue[this.observeAttr][this.telemetry] as Array; - let keyNameJson = this.configurationValue[this.observeAttr][this.keyName] as JsonObject; - if (this.includesInstancesNo(attributeArray, telemetryArray, clientObserveAttr)) { - this.addInstances(attributeArray, telemetryArray, clientObserveAttr); + const observeArray = this.configurationValue[this.observeAttr][this.observe]; + const attributeArray = this.configurationValue[this.observeAttr][this.attribute]; + const telemetryArray = this.configurationValue[this.observeAttr][this.telemetry]; + const keyNameJson = this.configurationValue[this.observeAttr][this.keyName]; + if (this.includesNotZeroInstance(attributeArray, telemetryArray)) { + this.addInstances(attributeArray, telemetryArray, clientObserveAttrTelemetry); + } + if (isDefinedAndNotNull(observeArray)) { + this.updateObserveAttrTelemetryObjects(observeArray, clientObserveAttrTelemetry, 'observe'); + } + if (isDefinedAndNotNull(attributeArray)) { + this.updateObserveAttrTelemetryObjects(attributeArray, clientObserveAttrTelemetry, 'attribute'); + } + if (isDefinedAndNotNull(telemetryArray)) { + this.updateObserveAttrTelemetryObjects(telemetryArray, clientObserveAttrTelemetry, 'telemetry'); + } + if (isDefinedAndNotNull(keyNameJson)) { + this.updateKeyNameObjects(keyNameJson, clientObserveAttrTelemetry); } - if (observeArray) this.updateObserveAttrTelemetryObjects(observeArray, clientObserveAttr, "observe"); - if (attributeArray) this.updateObserveAttrTelemetryObjects(attributeArray, clientObserveAttr, "attribute"); - if (telemetryArray) this.updateObserveAttrTelemetryObjects(telemetryArray, clientObserveAttr, "telemetry"); - if (keyNameJson) this.updateKeyNameObjects(deepClone(keyNameJson), clientObserveAttr); } - clientObserveAttr.forEach(obj => { - obj.instances.sort((a,b) => a.id - b.id);; - }) - return clientObserveAttr; + return {clientLwM2M: clientObserveAttrTelemetry}; } - includesInstancesNo(attributeArray: Array, telemetryArray: Array, clientObserveAttr: ObjectLwM2M[]): boolean { - let isIdIndex = (element) => !element.includes("/0/"); - return attributeArray.findIndex(isIdIndex) >= 0 || telemetryArray.findIndex(isIdIndex) >= 0 - + private includesNotZeroInstance = (attribute: string[], telemetry: string[]): boolean => { + const isNotZeroInstanceId = (instance) => !instance.includes('/0/'); + return attribute.some(isNotZeroInstanceId) || telemetry.some(isNotZeroInstanceId); } - addInstances(attributeArray: Array, telemetryArray: Array, clientObserveAttr: ObjectLwM2M[]): void { - let attr = [] as Array; - [...attributeArray].filter(x => (!x.includes("/0/"))).forEach(x => { - attr.push(this.convertPathToInstance(x)); - }); - let telemetry = [] as Array; - [...telemetryArray].filter(x => (!x.includes("/0/"))).forEach(x => { - telemetry.push(this.convertPathToInstance(x)); - }); - let instancesNoZero = new Set(attr.concat(telemetry).sort()); - instancesNoZero.forEach(path => { - let pathParameter = Array.from(path.split('/'), Number); - let objectLwM2M = clientObserveAttr.find(x => (x.id === pathParameter[0])); + private addInstances = (attribute: string[], telemetry: string[], clientObserveAttrTelemetry: ObjectLwM2M[]): void => { + const instancesPath = attribute.concat(telemetry) + .filter(instance => !instance.includes('/0/')) + .map(instance => instance.slice(1, instance.lastIndexOf('/'))) + .sort(this.sortPath); + + new Set(instancesPath).forEach(path => { + const pathParameter = Array.from(path.split('/'), Number); + const objectLwM2M = clientObserveAttrTelemetry.find(x => x.id === pathParameter[0]); if (objectLwM2M) { - let instance = deepClone(objectLwM2M.instances[0]) as Instance; + const instance = deepClone(objectLwM2M.instances[0]); instance.id = pathParameter[1]; objectLwM2M.instances.push(instance); } - }) - } - - convertPathToInstance(path: string): string { - let newX = Array.from(path.substring(1).split('/'), Number); - return [newX[0], newX[1]].join("/"); + }); } - updateObserveAttrTelemetryObjects(isParameter: Array, clientObserveAttr: ObjectLwM2M[], nameParameter: string): void { - isParameter.forEach(attr => { - let idKeys = Array.from(attr.substring(1).split('/'), Number); - clientObserveAttr - .forEach(e => { - if (e.id == idKeys[0]) { - let instance = e.instances.find(e => e.id == idKeys[1]); - if (isNotNullOrUndefined(instance)) { - instance.resources.find(e => e.id == idKeys[2])[nameParameter] = true; - } - } - }); + private updateObserveAttrTelemetryObjects = (parameters: string[], clientObserveAttrTelemetry: ObjectLwM2M[], + nameParameter: string): void => { + parameters.forEach(parameter => { + const [objectId, instanceId, resourceId] = Array.from(parameter.substring(1).split('/'), Number); + clientObserveAttrTelemetry.find(objectLwm2m => objectLwm2m.id === objectId) + .instances.find(itrInstance => itrInstance.id === instanceId) + .resources.find(resource => resource.id === resourceId) + [nameParameter] = true; }); } - updateKeyNameObjects(nameJson: JsonObject, clientObserveAttr: ObjectLwM2M[]): void { - let keyName = JSON.parse(JSON.stringify(nameJson)); - Object.keys(keyName).forEach(function (key) { - let idKeys = Array.from(key.substring(1).split('/'), Number); - clientObserveAttr - .forEach(e => { - if (e.id == idKeys[0]) { - e.instances.find(e => e.id == idKeys[1]).resources - .find(e => e.id == idKeys[2]).keyName = keyName[key]; - } - }); + private updateKeyNameObjects = (nameJson: JsonObject, clientObserveAttrTelemetry: ObjectLwM2M[]): void => { + const keyName = JSON.parse(JSON.stringify(nameJson)); + Object.keys(keyName).forEach(key => { + const [objectId, instanceId, resourceId] = Array.from(key.substring(1).split('/'), Number); + clientObserveAttrTelemetry.find(objectLwm2m => objectLwm2m.id === objectId) + .instances.find(instance => instance.id === instanceId) + .resources.find(resource => resource.id === resourceId) + .keyName = keyName[key]; }); } - upDateObserveAttrTelemetryFromGroupToJson(val: ObjectLwM2M []): void { - let observeArray = [] as Array; - let attributeArray = [] as Array; - let telemetryArray = [] as Array; - let observeJson = JSON.parse(JSON.stringify(val)); + private updateObserveAttrTelemetryFromGroupToJson = (val: ObjectLwM2M[]): void => { + const observeArray: Array = []; + const attributeArray: Array = []; + const telemetryArray: Array = []; + const keyNameNew = {}; + const observeJson: ObjectLwM2M[] = JSON.parse(JSON.stringify(val)); + const paths = new Set(); let pathObj; let pathInst; - let pathRes + let pathRes; observeJson.forEach(obj => { - Object.entries(obj).forEach(([key, value]) => { + for (const [key, value] of Object.entries(obj)) { if (key === 'id') { pathObj = value; } if (key === 'instances') { - let instancesJson = JSON.parse(JSON.stringify(value)) as []; + const instancesJson = value as Instance[]; if (instancesJson.length > 0) { instancesJson.forEach(instance => { - Object.entries(instance).forEach(([key, value]) => { - if (key === 'id') { - pathInst = value; + for (const [instanceKey, instanceValue] of Object.entries(instance)) { + if (instanceKey === 'id') { + pathInst = instanceValue; } - if (key === 'resources') { - let resourcesJson = JSON.parse(JSON.stringify(value)) as []; + if (instanceKey === 'resources') { + const resourcesJson = instanceValue as ResourceLwM2M[]; if (resourcesJson.length > 0) { resourcesJson.forEach(res => { - Object.entries(res).forEach(([key, value]) => { - if (key === 'id') { - // pathRes = value - pathRes = '/' + pathObj + '/' + pathInst + '/' + value; - } else if (key === 'observe' && value) { - observeArray.push(pathRes) - } else if (key === 'attribute' && value) { - attributeArray.push(pathRes) - } else if (key === 'telemetry' && value) { - telemetryArray.push(pathRes) + for (const [resourceKey, value] of Object.entries(res)) { + if (resourceKey === 'id') { + pathRes = `/${pathObj}/${pathInst}/${value}`; + } else if (resourceKey === 'observe' && value) { + observeArray.push(pathRes); + } else if (resourceKey === 'attribute' && value) { + attributeArray.push(pathRes); + paths.add(pathRes); + } else if (resourceKey === 'telemetry' && value) { + telemetryArray.push(pathRes); + paths.add(pathRes); + } + else if (resourceKey === this.keyName && paths.has(pathRes)) { + console.warn(pathRes, value); + keyNameNew[pathRes] = value; } - }); + } }); } } - }); + } }); } } - }); + } }); if (isUndefined(this.configurationValue[this.observeAttr])) { this.configurationValue[this.observeAttr] = { @@ -392,68 +331,34 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro this.configurationValue[this.observeAttr][this.attribute] = attributeArray; this.configurationValue[this.observeAttr][this.telemetry] = telemetryArray; } - this.updateKeyName(); - } - - sortObjectKeyPathJson(key, value) { - if (key == "keyName") { - return Object.keys(value).sort((a, b) => { - let aLC = Array.from(a.substring(1).split('/'), Number); - let bLC = Array.from(b.substring(1).split('/'), Number); - return aLC[0] == bLC[0] ? aLC[1] - bLC[1] : aLC[0] - bLC[0]; - }).reduce((r, k) => (r[k] = value[k], r), {}); + this.configurationValue[this.observeAttr][this.keyName] = this.sortObjectKeyPathJson('keyName', keyNameNew); + } + + sortObjectKeyPathJson = (key: string, value: object): object => { + if (key === 'keyName') { + return Object.keys(value).sort(this.sortPath).reduce((obj, keySort) => { + obj[keySort] = value[keySort]; + return obj; + }, {}); + } else if (key === 'observe' || key === 'attribute' || key === 'telemetry') { + return Object.values(value).sort(this.sortPath).reduce((arr, arrValue) => { + arr.push(arrValue); + return arr; + }, []); } else { - return value + return value; } } - updateKeyName(): void { - let paths = new Set(); - if (this.configurationValue[this.observeAttr][this.attribute]) { - this.configurationValue[this.observeAttr][this.attribute].forEach(path => { - paths.add(path); - }); - } - if (this.configurationValue[this.observeAttr][this.telemetry]) { - this.configurationValue[this.observeAttr][this.telemetry].forEach(path => { - paths.add(path); - }); - } - let keyNameNew = {}; - paths.forEach(path => { - let pathParameter = this.findIndexsForIds(path); - if (pathParameter.length === 3) { - let value = this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").value['clientLwM2M'][pathParameter[0]].instances[pathParameter[1]].resources[pathParameter[2]][this.keyName]; - keyNameNew[path] = value; - } + private sortPath = (a, b): number => { + return a.localeCompare(b, undefined, { + numeric: true, + sensitivity: 'base' }); - this.configurationValue[this.observeAttr][this.keyName] = this.sortObjectKeyPathJson("keyName", keyNameNew); } - findIndexsForIds(path: string): number[] { - let pathParameter = Array.from(path.substring(1).split('/'), Number); - let pathParameterIndexes = [] as number[]; - let objectsOld = deepClone(this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").value.clientLwM2M) as ObjectLwM2M[]; - let isIdIndex = (element) => element.id === pathParameter[0]; - let objIndex = objectsOld.findIndex(isIdIndex); - if (objIndex >= 0) { - pathParameterIndexes.push(objIndex); - isIdIndex = (element) => element.id === pathParameter[1]; - let instIndex = objectsOld[objIndex].instances.findIndex(isIdIndex); - if (instIndex >= 0) { - pathParameterIndexes.push(instIndex); - isIdIndex = (element) => element.id === pathParameter[2]; - let resIndex = objectsOld[objIndex].instances[instIndex].resources.findIndex(isIdIndex); - if (resIndex >= 0) { - pathParameterIndexes.push(resIndex); - } - } - } - return pathParameterIndexes; - } - - getObjectsFromJsonAllConfig(): number [] { - let objectsIds = new Set(); + private getObjectsFromJsonAllConfig = (): number[] => { + const objectsIds = new Set(); if (this.configurationValue[this.observeAttr]) { if (this.configurationValue[this.observeAttr][this.observe]) { this.configurationValue[this.observeAttr][this.observe].forEach(obj => { @@ -474,50 +379,45 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro return (objectsIds.size > 0) ? Array.from(objectsIds) : null; } - upDateJsonAllConfig(): void { - this.lwm2mDeviceProfileTransportConfFormGroup.patchValue({ + private upDateJsonAllConfig = (): void => { + this.lwm2mDeviceConfigFormGroup.patchValue({ configurationJson: this.configurationValue }, {emitEvent: false}); - this.lwm2mDeviceProfileTransportConfFormGroup.markAsPristine({ - onlySelf: true - }); } - addObjectsList(value: ObjectLwM2M[]): void { - this.updateObserveAttrTelemetryObjectFormGroup(deepClone(value)); + addObjectsList = (value: ObjectLwM2M[]): void => { + this.updateObserveAttrTelemetryObjectFormGroup(value); } - removeObjectsList(value: ObjectLwM2M): void { - let objectsOld = deepClone(this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").value.clientLwM2M); + removeObjectsList = (value: ObjectLwM2M): void => { + const objectsOld = this.lwm2mDeviceProfileFormGroup.get('observeAttrTelemetry').value.clientLwM2M; const isIdIndex = (element) => element.id === value.id; - let index = objectsOld.findIndex(isIdIndex); + const index = objectsOld.findIndex(isIdIndex); if (index >= 0) { objectsOld.splice(index, 1); } - this.updateObserveAttrTelemetryObjectFormGroup(objectsOld); this.removeObserveAttrTelemetryFromJson(this.observe, value.id); this.removeObserveAttrTelemetryFromJson(this.telemetry, value.id); this.removeObserveAttrTelemetryFromJson(this.attribute, value.id); - this.removeObserveAttrTelemetryFromJson(this.attribute, value.id); this.removeKeyNameFromJson(value.id); + this.updateObserveAttrTelemetryObjectFormGroup(objectsOld); this.upDateJsonAllConfig(); } - removeObserveAttrTelemetryFromJson(observeAttrTel: string, id: number): void { - let isIdIndex = (element) => Array.from(element.substring(1).split('/'), Number)[0] === id; + private removeObserveAttrTelemetryFromJson = (observeAttrTel: string, id: number): void => { + const isIdIndex = (element) => element.startsWith(`/${id}`); let index = this.configurationValue[this.observeAttr][observeAttrTel].findIndex(isIdIndex); while (index >= 0) { this.configurationValue[this.observeAttr][observeAttrTel].splice(index, 1); - index = this.configurationValue[this.observeAttr][observeAttrTel].findIndex(isIdIndex); + index = this.configurationValue[this.observeAttr][observeAttrTel].findIndex(isIdIndex, index); } } - removeKeyNameFromJson(id: number): void { - let keyNmaeJson = this.configurationValue[this.observeAttr][this.keyName]; - Object.keys(keyNmaeJson).forEach(function (key) { - let idKey = Array.from(key.substring(1).split('/'), Number)[0]; - if (idKey === id) { - delete keyNmaeJson[key]; + private removeKeyNameFromJson = (id: number): void => { + const keyNameJson = this.configurationValue[this.observeAttr][this.keyName]; + Object.keys(keyNameJson).forEach(key => { + if (key.startsWith(`/${id}`)) { + delete keyNameJson[key]; } }); } @@ -527,10 +427,10 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro if (!isPath) { isPath = this.findPathInJson(path, this.telemetry); } - return (isPath) ? true : false; + return !!isPath; } - findPathInJson(path: string, side: string): string { + private findPathInJson = (path: string, side: string): string => { if (this.configurationValue[this.observeAttr]) { if (this.configurationValue[this.observeAttr][side]) { return this.configurationValue[this.observeAttr][side].find( diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.html b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.html index cddc6f1ef5..34d77c299b 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.html @@ -15,43 +15,44 @@ limitations under the License. --> - - {{ 'device-profile.lwm2m.instances-list' | translate }} - - - {{instanceIdInputFor}} - close - - - {{ 'device-profile.lwm2m.instances-input' | translate }} - - - {{ translate.get('device-profile.lwm2m.valid-id-instance-no-min', { - instance: instanceIdInput.value.toString(), min: instanceIdValueMin.toString() - }) | async }} - - - {{ translate.get('device-profile.lwm2m.valid-id-instance-no-max', { - instance: instanceIdInput.value.toString(), max: instanceIdValueMax.toString() - }) | async }} - - - {{ translate.get('device-profile.lwm2m.instances-input-holder', { - instance: instanceIdInput.value.toString(), max: instanceIdValueMax.toString() - }) | async }} - - - - +
+ + {{ 'device-profile.lwm2m.instances-list' | translate }} + + + {{instanceId}} + close + + + + + {{ 'device-profile.lwm2m.instances-input' | translate }} + + + + {{ translate.get('device-profile.lwm2m.valid-id-instance', { + count: 2, instance: instanceId, min: instanceIdValueMin + }) | async }} + + + {{ translate.get('device-profile.lwm2m.valid-id-instance', { + count: 1, instance: instanceId, max: instanceIdValueMax + }) | async }} + + + {{ translate.get('device-profile.lwm2m.valid-id-instance', { + count: 0, instance: instanceId, max: instanceIdValueMax + }) | async }} + + +
diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.scss b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.scss deleted file mode 100644 index 45e601db09..0000000000 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.scss +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright © 2016-2020 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -:host ::ng-deep { - mat-form-field.lwm2m-instances-list { - & > .mat-form-field-wrapper > .mat-form-field-underline { - display: none; - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.ts b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.ts index 20a72d8dcd..1921db396d 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.ts @@ -14,88 +14,48 @@ /// limitations under the License. /// -import { - Component, - forwardRef, - Input, - OnInit, - ViewChild, - ElementRef, -} from "@angular/core"; -import { - ControlValueAccessor, - FormBuilder, - FormGroup, NG_VALIDATORS, - NG_VALUE_ACCESSOR, Validators -} from "@angular/forms"; -import { coerceBooleanProperty } from "@angular/cdk/coercion"; -import { Store } from "@ngrx/store"; -import { AppState } from "../../../../../../core/core.state"; -import { MatChipList } from '@angular/material/chips'; -import { - INSTANCES_ID_VALUE_MAX, - INSTANCES_ID_VALUE_MIN -} from "./profile-config.models"; -import { TranslateService } from "@ngx-translate/core"; -import { DeviceProfileService } from "../../../../../../core/http/device-profile.service"; +import { Component, forwardRef, } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { INSTANCES_ID_VALUE_MAX, INSTANCES_ID_VALUE_MIN, KEY_REGEXP_NUMBER } from './profile-config.models'; +import { TranslateService } from '@ngx-translate/core'; +import { DeviceProfileService } from '@core/http/device-profile.service'; @Component({ selector: 'tb-profile-lwm2m-object-add-instances-list', templateUrl: './lwm2m-object-add-instances-list.component.html', - styleUrls: ['./lwm2m-object-add-instances-list.component.scss'], + styleUrls: [], providers: [{ - provide: NG_VALUE_ACCESSOR, - useExisting: forwardRef(() => Lwm2mObjectAddInstancesListComponent), - multi: true - }] + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => Lwm2mObjectAddInstancesListComponent), + multi: true + }] }) -export class Lwm2mObjectAddInstancesListComponent implements ControlValueAccessor, OnInit, Validators { +export class Lwm2mObjectAddInstancesListComponent implements ControlValueAccessor { - lwm2mObjectListFormGroup: FormGroup; - private requiredValue: boolean; - private instancesIdsList: Set | null; - filteredObjectsList: Array; - private disabled = false as boolean; - private dirty = false as boolean; - instanceIdValueMin = INSTANCES_ID_VALUE_MIN as number - instanceIdValueMax = INSTANCES_ID_VALUE_MAX as number + private disabled = false; + private dirty = false; - get required(): boolean { - return this.requiredValue; - } - - @Input() - set required(value: boolean) { - const newVal = coerceBooleanProperty(value); - if (this.requiredValue !== newVal) { - this.requiredValue = newVal; - this.updateValidators(); - } - } - - @ViewChild('instanceIdInput') instanceIdInput: ElementRef; - @ViewChild('chipList', {static: true}) chipList: MatChipList; + instancesListFormGroup: FormGroup; + instancesId = new Set(); + instanceIdValueMin = INSTANCES_ID_VALUE_MIN; + instanceIdValueMax = INSTANCES_ID_VALUE_MAX; - private propagateChange = (v: any) => { - }; + private propagateChange = (v: any) => { }; constructor(private store: Store, public translate: TranslateService, private deviceProfileService: DeviceProfileService, private fb: FormBuilder) { - this.lwm2mObjectListFormGroup = this.fb.group({ - instancesIdsList: [null], - instanceIdInput: [null] + this.instancesListFormGroup = this.fb.group({ + instanceIdInput: [null, [ + Validators.min(this.instanceIdValueMin), + Validators.max(this.instanceIdValueMax), + Validators.pattern(KEY_REGEXP_NUMBER)]] }); } - updateValidators() { - this.lwm2mObjectListFormGroup.get('instanceIdInput').setValidators([ - Validators.min(this.instanceIdValueMin), - Validators.max(this.instanceIdValueMax)]); - this.lwm2mObjectListFormGroup.get('instanceIdInput').updateValueAndValidity(); - } - registerOnChange(fn: any): void { this.propagateChange = fn; } @@ -103,77 +63,38 @@ export class Lwm2mObjectAddInstancesListComponent implements ControlValueAccesso registerOnTouched(fn: any): void { } - ngOnInit() { - } - - ngAfterViewInit(): void { - } - setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; if (isDisabled) { - this.lwm2mObjectListFormGroup.disable({emitEvent: false}); + this.instancesListFormGroup.disable({emitEvent: false}); } else { - this.lwm2mObjectListFormGroup.enable({emitEvent: false}); + this.instancesListFormGroup.enable({emitEvent: false}); } } writeValue(value: Set): void { - this.instancesIdsList = new Set(); if (value && value.size) { - value.forEach(item => this.instancesIdsList.add(item)); - this.lwm2mObjectListFormGroup.get('instancesIdsList').setValue(this.instancesIdsList); + this.instancesId = value; } - this.updateValidators(); this.dirty = false; } - add(value: number): void { - if (!isNaN(value) && this.lwm2mObjectListFormGroup.get('instanceIdInput').valid) { - this.instancesIdsList.add(value); - this.lwm2mObjectListFormGroup.get('instancesIdsList').setValue(this.instancesIdsList); - this.propagateChange(this.instancesIdsList); - this.dirty = true + add = (): void => { + if (this.instancesListFormGroup.get('instanceIdInput').valid && Number.isFinite(Number(this.instanceId))) { + this.instancesId.add(Number(this.instanceId)); + this.instancesListFormGroup.get('instanceIdInput').setValue(null); + this.propagateChange(this.instancesId); + this.dirty = true; } - this.clear(); - } - - remove(object: number) { - this.instancesIdsList.delete(object); - this.lwm2mObjectListFormGroup.get('instancesIdsList').setValue(this.instancesIdsList); - this.propagateChange(this.instancesIdsList); - this.dirty = true - this.clear(); - } - - displayFn(object?: number): number | undefined { - return object ? object : undefined; } - clear() { - this.lwm2mObjectListFormGroup.get('instanceIdInput').patchValue(null, {emitEvent: true}); - this.instanceIdInput.nativeElement.value = ""; - setTimeout(() => { - this.instanceIdInput.nativeElement.blur(); - this.instanceIdInput.nativeElement.focus(); - }, 0); + remove = (object: number): void => { + this.instancesId.delete(object); + this.propagateChange(this.instancesId); + this.dirty = true; } - onkeydown(e: KeyboardEvent) { - if (e.keyCode == 189 || e.keyCode == 187 || e.keyCode == 109 || e.keyCode == 107) { - return false; - } else if (e.keyCode == 8) { - if (this.lwm2mObjectListFormGroup.get('instanceIdInput').value == null) { - this.clear(); - } - this.instanceIdInput.nativeElement.focus(); - } - } - - onFocus() { - if (this.dirty) { - this.lwm2mObjectListFormGroup.get('instanceIdInput').updateValueAndValidity({onlySelf: true, emitEvent: true}); - this.dirty = false; - } + get instanceId(): number { + return this.instancesListFormGroup.get('instanceIdInput').value; } } diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances.component.html b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances.component.html index b8d10689e1..303e38f180 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances.component.html @@ -15,7 +15,7 @@ limitations under the License. --> -
+ {{data.objectName}}    (object [{{data.objectId}}]) @@ -30,24 +30,21 @@
-
- - -
+ +
- -
diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances.component.ts b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances.component.ts index 62f516b660..57c7e3e2b5 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances.component.ts @@ -16,12 +16,11 @@ import { Component, Inject, OnInit } from '@angular/core'; import { DialogComponent } from '@shared/components/dialog.component'; -import { ControlValueAccessor, FormBuilder, FormGroup } from '@angular/forms'; +import { FormBuilder, FormGroup } from '@angular/forms'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { Router } from '@angular/router'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; -import { TranslateService } from '@ngx-translate/core'; export interface Lwm2mObjectAddInstancesData { instancesIds: Set; @@ -36,9 +35,7 @@ export interface Lwm2mObjectAddInstancesData { }) export class Lwm2mObjectAddInstancesComponent extends DialogComponent implements OnInit { - jsonFormGroup: FormGroup; - // title: string; - + instancesFormGroup: FormGroup; submitted = false; constructor(protected store: Store, @@ -49,11 +46,10 @@ export class Lwm2mObjectAddInstancesComponent extends DialogComponent - + - + @@ -49,7 +49,7 @@ - + {{ 'device-profile.lwm2m.object-list-empty' | translate }} diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-list.component.ts b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-list.component.ts index b0f9ea4ebf..3062c52ed3 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-list.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-list.component.ts @@ -14,39 +14,22 @@ /// limitations under the License. /// -import { - Component, - forwardRef, - Input, - OnInit, - ViewChild, - ElementRef, - Output, - EventEmitter -} from "@angular/core"; -import { - ControlValueAccessor, - FormBuilder, - FormGroup, - NG_VALUE_ACCESSOR, Validators -} from "@angular/forms"; -import {coerceBooleanProperty} from "@angular/cdk/coercion"; -import {Store} from "@ngrx/store"; -import {AppState} from "../../../../../../core/core.state"; -import {MatChipList} from '@angular/material/chips'; -import {MatAutocomplete} from "@angular/material/autocomplete"; -import {Observable} from "rxjs"; -import {filter, map, mergeMap, share, tap} from 'rxjs/operators'; -import {ObjectLwM2M} from "./profile-config.models"; -import {TranslateService} from "@ngx-translate/core"; -import {DeviceProfileService} from "../../../../../../core/http/device-profile.service"; -import {PageLink} from "../../../../../../shared/models/page/page-link"; -import {Direction} from "../../../../../../shared/models/page/sort-order"; +import { Component, ElementRef, EventEmitter, forwardRef, Input, OnInit, Output, ViewChild } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { Observable } from 'rxjs'; +import { filter, map, mergeMap, publishReplay, refCount, tap } from 'rxjs/operators'; +import { ObjectLwM2M } from './profile-config.models'; +import { TranslateService } from '@ngx-translate/core'; +import { DeviceProfileService } from '@core/http/device-profile.service'; +import { Direction } from '@shared/models/page/sort-order'; +import { isDefined, isDefinedAndNotNull, isEmptyStr, isString } from '@core/utils'; @Component({ selector: 'tb-profile-lwm2m-object-list', templateUrl: './lwm2m-object-list.component.html', - styleUrls: [], providers: [ { provide: NG_VALUE_ACCESSOR, @@ -56,14 +39,16 @@ import {Direction} from "../../../../../../shared/models/page/sort-order"; }) export class Lwm2mObjectListComponent implements ControlValueAccessor, OnInit, Validators { - lwm2mObjectListFormGroup: FormGroup; private requiredValue: boolean; - modelValue: Array | null; + private dirty = false; + private lw2mModels: Observable>; + private modelValue: Array = []; + + lwm2mListFormGroup: FormGroup; objectsList: Array = []; filteredObjectsList: Observable>; - private disabled = false as boolean; - searchText = '' as string; - private dirty = false as boolean; + disabled = false; + searchText = ''; get required(): boolean { return this.requiredValue; @@ -71,11 +56,8 @@ export class Lwm2mObjectListComponent implements ControlValueAccessor, OnInit, V @Input() set required(value: boolean) { - const newVal = coerceBooleanProperty(value); - if (this.requiredValue !== newVal) { - this.requiredValue = newVal; - this.updateValidators(); - } + this.requiredValue = coerceBooleanProperty(value); + this.updateValidators(); } @Output() @@ -85,25 +67,23 @@ export class Lwm2mObjectListComponent implements ControlValueAccessor, OnInit, V removeList = new EventEmitter(); @ViewChild('objectInput') objectInput: ElementRef; - @ViewChild('objectAutocomplete') matAutocomplete: MatAutocomplete; - @ViewChild('chipList', {static: true}) chipList: MatChipList; private propagateChange = (v: any) => { - }; + } constructor(private store: Store, public translate: TranslateService, private deviceProfileService: DeviceProfileService, private fb: FormBuilder) { - this.lwm2mObjectListFormGroup = this.fb.group({ + this.lwm2mListFormGroup = this.fb.group({ objectsList: [this.objectsList], - objectLwm2m: [null, this.required ? [Validators.required] : []] + objectLwm2m: [''] }); } - updateValidators() { - this.lwm2mObjectListFormGroup.get('objectLwm2m').setValidators(this.required ? [Validators.required] : []); - this.lwm2mObjectListFormGroup.get('objectLwm2m').updateValueAndValidity(); + private updateValidators = (): void => { + this.lwm2mListFormGroup.get('objectLwm2m').setValidators(this.required ? [Validators.required] : []); + this.lwm2mListFormGroup.get('objectLwm2m').updateValueAndValidity(); } registerOnChange(fn: any): void { @@ -114,118 +94,117 @@ export class Lwm2mObjectListComponent implements ControlValueAccessor, OnInit, V } ngOnInit() { - this.filteredObjectsList = this.lwm2mObjectListFormGroup.get('objectLwm2m').valueChanges + this.filteredObjectsList = this.lwm2mListFormGroup.get('objectLwm2m').valueChanges .pipe( tap((value) => { if (value && typeof value !== 'string') { this.add(value); } else if (value === null) { - this.clear(this.objectInput.nativeElement.value); + this.clear(); } }), - filter((value) => typeof value === 'string'), - map((value) => value ? (typeof value === 'string' ? value : value.name) : ''), - mergeMap(name => this.fetchListObjects(name)), - share() + filter(searchText => isString(searchText)), + mergeMap(searchText => this.fetchListObjects(searchText)) ); } - ngAfterViewInit(): void { - } - setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; if (isDisabled) { - this.lwm2mObjectListFormGroup.disable({emitEvent: false}); + this.lwm2mListFormGroup.disable({emitEvent: false}); + if (isDefined(this.objectInput)) { + this.clear(); + } } else { - this.lwm2mObjectListFormGroup.enable({emitEvent: false}); + this.lwm2mListFormGroup.enable({emitEvent: false}); } } writeValue(value: any): void { this.searchText = ''; - if (value.hasOwnProperty("objectIds") && value["objectIds"] != null && value["objectIds"].length > 0) { - this.modelValue = [...value["objectIds"]]; - this.objectsList = value["objectsList"]; - this.lwm2mObjectListFormGroup.get('objectsList').setValue(this.objectsList); - } else { - this.objectsList = []; - this.lwm2mObjectListFormGroup.get('objectsList').setValue(this.objectsList); - this.modelValue = null; - } - this.dirty = true; - } - - reset() { - this.objectsList = []; - this.lwm2mObjectListFormGroup.get('objectsList').setValue(this.objectsList); - this.modelValue = null; - if (this.objectInput) { - this.objectInput.nativeElement.value = ''; + if (isDefinedAndNotNull(value)) { + if (Array.isArray(value.objectIds)) { + this.modelValue = value.objectIds; + this.objectsList = value.objectsList; + } else { + this.objectsList = []; + this.modelValue = []; + } + this.lwm2mListFormGroup.get('objectsList').setValue(this.objectsList, {emitEvents: false}); + this.dirty = false; } - this.lwm2mObjectListFormGroup.get('objectLwm2m').patchValue('', {emitEvent: false}); - this.propagateChange(this.modelValue); - this.dirty = true; } - add(object: ObjectLwM2M): void { - if (!this.modelValue || this.modelValue.indexOf(object.id) === -1) { - if (!this.modelValue) { - this.modelValue = []; - } + private add(object: ObjectLwM2M): void { + if (this.modelValue.indexOf(object.id) === -1) { this.modelValue.push(object.id); this.objectsList.push(object); - this.lwm2mObjectListFormGroup.get('objectsList').setValue(this.objectsList); + this.lwm2mListFormGroup.get('objectsList').setValue(this.objectsList); this.addList.next(this.objectsList); } - this.propagateChange(this.modelValue); this.clear(); } - remove(object: ObjectLwM2M) { + remove = (object: ObjectLwM2M): void => { let index = this.objectsList.indexOf(object); if (index >= 0) { this.objectsList.splice(index, 1); - this.lwm2mObjectListFormGroup.get('objectsList').setValue(this.objectsList); + this.lwm2mListFormGroup.get('objectsList').setValue(this.objectsList); index = this.modelValue.indexOf(object.id); this.modelValue.splice(index, 1); this.removeList.next(object); if (!this.modelValue.length) { this.modelValue = null; } - this.propagateChange(this.modelValue); this.clear(); } } - displayObjectLwm2mFn(object?: ObjectLwM2M): string | undefined { + displayObjectLwm2mFn = (object?: ObjectLwM2M): string | undefined => { return object ? object.name : undefined; } - fetchListObjects(searchText?: string): Observable> { + private fetchListObjects = (searchText?: string): Observable> => { this.searchText = searchText; - const pageLink = new PageLink(10, 0, searchText, { - property: 'name', - direction: Direction.ASC - }); - return this.deviceProfileService.getLwm2mObjectsPage(pageLink, {ignoreLoading: true}).pipe( - map(pageData => { - let data = pageData.data; - return data; - }) + const filters = {names: [], ids: []}; + if (isDefinedAndNotNull(searchText) && !isEmptyStr(searchText)) { + const ids = searchText.match(/\d+/g); + filters.ids = ids !== null ? ids.map(Number) : filters.ids; + filters.names = searchText.trim().toUpperCase().split(' '); + } + const predicate = objectLwM2M => filters.names.find(word => objectLwM2M.name.toUpperCase().includes(word)) + || filters.ids.includes(objectLwM2M.id); + return this.getLwM2mModels().pipe( + map(objectLwM2Ms => searchText ? objectLwM2Ms.filter(predicate) : objectLwM2Ms) ); } - onFocus() { - if (this.dirty) { - this.lwm2mObjectListFormGroup.get('objectLwm2m').updateValueAndValidity({onlySelf: true, emitEvent: true}); - this.dirty = false; + private getLwM2mModels(): Observable> { + if (!this.lw2mModels) { + const sortOrder = { + property: 'name', + direction: Direction.ASC + }; + this.lw2mModels = this.deviceProfileService.getLwm2mObjects(sortOrder).pipe( + publishReplay(1), + refCount() + ); + } + return this.lw2mModels; + } + + + onFocus = (): void => { + if (!this.dirty) { + this.lwm2mListFormGroup.get('objectLwm2m').updateValueAndValidity({onlySelf: true, emitEvent: true}); + this.dirty = true; } } - clear(value: string = '') { + private clear = (value: string = ''): void => { this.objectInput.nativeElement.value = value; - this.lwm2mObjectListFormGroup.get('objectLwm2m').patchValue(value, {emitEvent: true}); + this.searchText = ''; + this.lwm2mListFormGroup.get('objectLwm2m').patchValue(value); setTimeout(() => { this.objectInput.nativeElement.blur(); this.objectInput.nativeElement.focus(); diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry-resource.component.html b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry-resource.component.html index 322fba8086..c406cfb17f 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry-resource.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry-resource.component.html @@ -17,12 +17,10 @@ -->
-
-
-
- -
+ *ngFor="let resourceLwM2M of resourceFormArray.controls; let i = index; trackBy: trackByParams"> +
+
+
device-profile.lwm2m.observe-label @@ -72,10 +70,9 @@ {{ 'device-profile.lwm2m.key-name_label' | translate }} - {{ 'device-profile.lwm2m.key-name' | translate }} {{ 'device-profile.lwm2m.required' | translate }} diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry-resource.component.ts b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry-resource.component.ts index f94cd589ae..8d3fa0c57b 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry-resource.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry-resource.component.ts @@ -14,20 +14,12 @@ /// limitations under the License. /// -import { Component, EventEmitter, forwardRef, Input, OnInit, Output, ViewChild } from "@angular/core"; -import { - ControlValueAccessor, - FormArray, FormBuilder, - FormGroup, - NG_VALUE_ACCESSOR, Validators -} from "@angular/forms"; -import { - CAMEL_CASE_REGEXP, - ResourceLwM2M -} from '@home/components/profile/device/lwm2m/profile-config.models'; +import { Component, forwardRef, Input } from '@angular/core'; +import { ControlValueAccessor, FormArray, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { ResourceLwM2M } from '@home/components/profile/device/lwm2m/profile-config.models'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; -import { deepClone, isUndefined } from '@core/utils'; +import _ from 'lodash'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; @Component({ @@ -43,13 +35,13 @@ import { coerceBooleanProperty } from '@angular/cdk/coercion'; ] }) -export class Lwm2mObserveAttrTelemetryResourceComponent implements ControlValueAccessor, OnInit, Validators { +export class Lwm2mObserveAttrTelemetryResourceComponent implements ControlValueAccessor { - resourceFormGroup : FormGroup; - - disabled = false as boolean; private requiredValue: boolean; + resourceFormGroup: FormGroup; + disabled = false; + get required(): boolean { return this.requiredValue; } @@ -61,9 +53,12 @@ export class Lwm2mObserveAttrTelemetryResourceComponent implements ControlValueA this.requiredValue = newVal; } } + constructor(private store: Store, private fb: FormBuilder) { - this.resourceFormGroup = this.fb.group({'resources': this.fb.array([])}); + this.resourceFormGroup = this.fb.group({ + resources: this.fb.array([]) + }); this.resourceFormGroup.valueChanges.subscribe(value => { if (!this.disabled) { this.propagateChangeState(value.resources); @@ -71,9 +66,6 @@ export class Lwm2mObserveAttrTelemetryResourceComponent implements ControlValueA }); } - ngOnInit(): void { - } - registerOnTouched(fn: any): void { } @@ -85,10 +77,6 @@ export class Lwm2mObserveAttrTelemetryResourceComponent implements ControlValueA return this.resourceFormGroup.get('resources') as FormArray; } - resourceLwm2mFormArray(instance: FormGroup): FormArray { - return instance.get('resources') as FormArray; - } - setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; if (isDisabled) { @@ -98,31 +86,16 @@ export class Lwm2mObserveAttrTelemetryResourceComponent implements ControlValueA } } - getDisabledState(): boolean { - return this.disabled; - } - - updateValueKeyName (event: any, z: number): void { - this.resourceFormArray.at(z).patchValue( {keyName: this.keysToCamel(deepClone(event.target.value))} ); - } - - keysToCamel(o: any): string { - let val = o.split(" "); - let playStore = []; - val.forEach(function (item, k){ - item = item.replace(CAMEL_CASE_REGEXP, ''); - item = (k===0)? item.charAt(0).toLowerCase() + item.substr(1) : item.charAt(0).toUpperCase() + item.substr(1) - playStore.push(item); - }); - return playStore.join(''); + updateValueKeyName = (event: Event, index: number): void => { + this.resourceFormArray.at(index).patchValue({keyName: _.camelCase((event.target as HTMLInputElement).value)}); } - createResourceLwM2M(resourcesLwM2MJson: ResourceLwM2M []): void { - if(resourcesLwM2MJson.length === this.resourceFormArray.length) { - this.resourceFormArray.patchValue(resourcesLwM2MJson, {emitEvent: false}) + createResourceLwM2M(resourcesLwM2M: ResourceLwM2M[]): void { + if (resourcesLwM2M.length === this.resourceFormArray.length) { + this.resourceFormArray.patchValue(resourcesLwM2M, {emitEvent: false}); } else { this.resourceFormArray.clear(); - resourcesLwM2MJson.forEach(resourceLwM2M => { + resourcesLwM2M.forEach(resourceLwM2M => { this.resourceFormArray.push(this.fb.group({ id: resourceLwM2M.id, name: resourceLwM2M.name, @@ -131,18 +104,17 @@ export class Lwm2mObserveAttrTelemetryResourceComponent implements ControlValueA telemetry: resourceLwM2M.telemetry, keyName: [resourceLwM2M.keyName, Validators.required] })); - }) + }); } } - private propagateChange = (v: any) => { - }; + private propagateChange = (v: any) => { }; registerOnChange(fn: any): void { this.propagateChange = fn; } - private propagateChangeState(value: any): void { + private propagateChangeState = (value: any): void => { if (value && this.resourceFormGroup.valid) { this.propagateChange(value); } else { @@ -150,7 +122,7 @@ export class Lwm2mObserveAttrTelemetryResourceComponent implements ControlValueA } } - trackByParams(index: number): number { + trackByParams = (index: number): number => { return index; } } diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry.component.html b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry.component.html index ea3233f769..7b33264ba6 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry.component.html @@ -16,26 +16,27 @@ --> -
+
- -
{{ objectLwM2M.get('name').value}} (object [{{ objectLwM2M.get('id').value}}])
- + + {{ objectLwM2M.get('name').value}} <id: {{ objectLwM2M.get('id').value}}> + + +
-
- + +
-
- - -
+
+
diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry.component.ts b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry.component.ts index 8482fde97a..b208ed7e14 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-observe-attr-telemetry.component.ts @@ -15,7 +15,7 @@ /// -import { Component, forwardRef, Input, OnInit, Output } from "@angular/core"; +import { Component, forwardRef, Input } from '@angular/core'; import { AbstractControl, ControlValueAccessor, @@ -24,27 +24,18 @@ import { FormGroup, NG_VALUE_ACCESSOR, Validators -} from "@angular/forms"; -import { Store } from "@ngrx/store"; -import { AppState } from "@core/core.state"; -import { coerceBooleanProperty } from "@angular/cdk/coercion"; -import { - ATTR, - Instance, - ObjectLwM2M, - OBSERVE, - ResourceLwM2M, - TELEMETRY -} from "./profile-config.models"; -import { isNotNullOrUndefined } from 'codelyzer/util/isNotNullOrUndefined'; -import { deepClone, isUndefined } from '@core/utils'; +} from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; +import { Instance, ObjectLwM2M, ResourceLwM2M } from './profile-config.models'; +import { deepClone, isDefinedAndNotNull, isEqual, isUndefined } from '@core/utils'; import { MatDialog } from '@angular/material/dialog'; import { TranslateService } from '@ngx-translate/core'; import { Lwm2mObjectAddInstancesComponent, Lwm2mObjectAddInstancesData } from '@home/components/profile/device/lwm2m/lwm2m-object-add-instances.component'; -import { Control } from 'leaflet'; @Component({ selector: 'tb-profile-lwm2m-observe-attr-telemetry', @@ -59,22 +50,17 @@ import { Control } from 'leaflet'; ] }) -export class Lwm2mObserveAttrTelemetryComponent implements ControlValueAccessor, OnInit, Validators { +export class Lwm2mObserveAttrTelemetryComponent implements ControlValueAccessor { + + private requiredValue: boolean; valuePrev = null as any; observeAttrTelemetryFormGroup: FormGroup; - observe = OBSERVE as string; - attribute = ATTR as string; - telemetry = TELEMETRY as string; - private requiredValue: boolean; get required(): boolean { return this.requiredValue; } - @Input() - disabled: boolean; - @Input() set required(value: boolean) { const newVal = coerceBooleanProperty(value); @@ -84,10 +70,13 @@ export class Lwm2mObserveAttrTelemetryComponent implements ControlValueAccessor, } } + @Input() + disabled: boolean; + constructor(private store: Store, private fb: FormBuilder, private dialog: MatDialog, - private translate: TranslateService) { + public translate: TranslateService) { this.observeAttrTelemetryFormGroup = this.fb.group({ clientLwM2M: this.fb.array([]) }); @@ -98,22 +87,17 @@ export class Lwm2mObserveAttrTelemetryComponent implements ControlValueAccessor, }); } - ngOnInit(): void { - } - - private propagateChange = (v: any) => { - }; - + private propagateChange = (v: any) => { }; registerOnChange(fn: any): void { this.propagateChange = fn; } - private propagateChangeState(value: any): void { + private propagateChangeState = (value: any): void => { if (value) { if (this.valuePrev === null) { - this.valuePrev = "init"; - } else if (this.valuePrev === "init") { + this.valuePrev = 'init'; + } else if (this.valuePrev === 'init') { this.valuePrev = value; } else if (JSON.stringify(value) !== JSON.stringify(this.valuePrev)) { this.valuePrev = value; @@ -139,92 +123,78 @@ export class Lwm2mObserveAttrTelemetryComponent implements ControlValueAccessor, } } - getDisabledState(): boolean { - return this.disabled; - } - writeValue(value: any): void { - this.buildClientObjectsLwM2M(value.clientLwM2M); + if (isDefinedAndNotNull(value)) { + this.buildClientObjectsLwM2M(value.clientLwM2M); + } } - private buildClientObjectsLwM2M(objectsLwM2M: ObjectLwM2M []): void { + private buildClientObjectsLwM2M = (objectsLwM2M: ObjectLwM2M []): void => { this.observeAttrTelemetryFormGroup.setControl('clientLwM2M', this.createObjectsLwM2M(objectsLwM2M) ); } - createObjectsLwM2M(objectsLwM2MJson: ObjectLwM2M []): FormArray { - return this.fb.array(objectsLwM2MJson.map((objectLwM2M) => { + private createObjectsLwM2M = (objectsLwM2M: ObjectLwM2M[]): FormArray => { + return this.fb.array(objectsLwM2M.map((objectLwM2M) => { return this.fb.group({ id: objectLwM2M.id, name: objectLwM2M.name, multiple: objectLwM2M.multiple, mandatory: objectLwM2M.mandatory, instances: this.createInstanceLwM2M(objectLwM2M.instances) - }) - })) + }); + })); } - createInstanceLwM2M(instanceLwM2MJson: Instance []): FormArray { - return this.fb.array(instanceLwM2MJson.map((instanceLwM2M, index) => { + private createInstanceLwM2M = (instancesLwM2M: Instance[]): FormArray => { + return this.fb.array(instancesLwM2M.map((instanceLwM2M) => { return this.fb.group({ id: instanceLwM2M.id, - [this.observe]: {value: false, disabled: this.disabled}, - [this.attribute]: {value: false, disabled: this.disabled}, - [this.telemetry]: {value: false, disabled: this.disabled}, resources: {value: instanceLwM2M.resources, disabled: this.disabled} - }) - })) + }); + })); } - clientLwM2MFormArray(formGroup: FormGroup): FormArray { - return formGroup.get('clientLwM2M') as FormArray; + get clientLwM2MFormArray(): FormArray { + return this.observeAttrTelemetryFormGroup.get('clientLwM2M') as FormArray; } - instancesLwm2mFormArray(objectLwM2M: AbstractControl): FormArray { + instancesLwm2mFormArray = (objectLwM2M: AbstractControl): FormArray => { return objectLwM2M.get('instances') as FormArray; } - changeInstanceResourcesCheckBox(value: boolean, instance: AbstractControl, type: string): void { - let resources = instance.get('resources').value as ResourceLwM2M [] + changeInstanceResourcesCheckBox = (value: boolean, instance: AbstractControl, type: string): void => { + const resources = deepClone(instance.get('resources').value as ResourceLwM2M[]); resources.forEach(resource => resource[type] = value); instance.get('resources').patchValue(resources); this.propagateChange(this.observeAttrTelemetryFormGroup.value); } - updateValidators() { - this.observeAttrTelemetryFormGroup.get('clientLwM2M').setValidators(this.required ? [Validators.required] : []); + private updateValidators = (): void => { + this.observeAttrTelemetryFormGroup.get('clientLwM2M').setValidators(this.required ? Validators.required : []); this.observeAttrTelemetryFormGroup.get('clientLwM2M').updateValueAndValidity(); } - trackByParams(index: number): number { + trackByParams = (index: number, element: any): number => { return index; } - getIndeterminate(instance: AbstractControl, type: string) { - const resources = instance.get('resources').value as ResourceLwM2M []; - if (isNotNullOrUndefined(resources)) { - const isType = (element) => element[type] === true; - let checkedResource = resources.filter(isType); - if (checkedResource.length === 0) return false; - else if (checkedResource.length === resources.length) { - instance.patchValue({[type]: true}); - return false; - } else return true; + getIndeterminate = (instance: AbstractControl, type: string): boolean => { + const resources = instance.get('resources').value as ResourceLwM2M[]; + if (isDefinedAndNotNull(resources)) { + const checkedResource = resources.filter(resource => resource[type]); + return checkedResource.length !== 0 && checkedResource.length !== resources.length; } return false; } - - getChecked(instance: AbstractControl, type: string) { - const resources = instance.get('resources').value as ResourceLwM2M []; - if (isNotNullOrUndefined(resources)) { - return resources.some(resource => resource[type]); - } - return false; + getChecked = (instance: AbstractControl, type: string): boolean => { + const resources = instance.get('resources').value as ResourceLwM2M[]; + return isDefinedAndNotNull(resources) && resources.every(resource => resource[type]); } - getExpended(objectLwM2M: AbstractControl) { + getExpended = (objectLwM2M: AbstractControl): boolean => { return this.instancesLwm2mFormArray(objectLwM2M).length === 1; } @@ -234,119 +204,96 @@ export class Lwm2mObserveAttrTelemetryComponent implements ControlValueAccessor, * 2) Field in object: == Mandatory/Optional * If this field is “Multiple” then the number of Object Instance can be from 0 to many (Object Instance ID MAX_ID=65535). * If this field is “Single” then the number of Object Instance can be from 0 to 1. (max count == 1) - * If the Object field “Mandatory” is “Mandatory” and the Object field “Instances” is “Single” then, the number of Object Instance MUST be 1. - * 1. == Multiple (true), == Optional (false) => Object Instance ID MIN_ID=0 MAX_ID=65535 (может ни одного не быть) - * 2. == Multiple (true), == Mandatory (true) => Object Instance ID MIN_ID=0 MAX_ID=65535 (min один обязательный) - * 3. == Single (false), == Optional (false) => Object Instance ID cnt_max = 1 cnt_min = 0 (может ни одного не быть) - * 4. == Single (false), == Mandatory (true) => Object Instance ID cnt_max = cnt_min = 1 (всегда есть один) - * @param $event - * @param objectId - * @param objectName + * If the Object field “Mandatory” is “Mandatory” and the Object field “Instances” is “Single” then - + * the number of Object Instance MUST be 1. + * 1. == Multiple (true), == Optional (false) - + * Object Instance ID MIN_ID=0 MAX_ID=65535 (может ни одного не быть) + * 2. == Multiple (true), == Mandatory (true) - + * Object Instance ID MIN_ID=0 MAX_ID=65535 (min один обязательный) + * 3. == Single (false), == Optional (false) - + * Object Instance ID cnt_max = 1 cnt_min = 0 (может ни одного не быть) + * 4. == Single (false), == Mandatory (true) - + * Object Instance ID cnt_max = cnt_min = 1 (всегда есть один) */ - addInstances($event: Event, object: ObjectLwM2M): void { + addInstances = ($event: Event, object: ObjectLwM2M): void => { if ($event) { $event.stopPropagation(); $event.preventDefault(); } - let instancesIds = new Set(); - object.instances.forEach(inst => { - instancesIds.add(inst.id); - }); this.dialog.open(Lwm2mObjectAddInstancesComponent, { disableClose: true, panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], data: { - instancesIds: this.setInstancesIds(object.instances), + instancesIds: this.instancesToSetId(object.instances), objectName: object.name, objectId: object.id } }).afterClosed().subscribe( (res: Lwm2mObjectAddInstancesData | undefined) => { - if (isNotNullOrUndefined(res)) { + if (isDefinedAndNotNull(res)) { this.updateInstancesIds(res); } } ); } - updateInstancesIds(data: Lwm2mObjectAddInstancesData) { - let valueNew = new Set(); - let valueOld = new Set(); - data.instancesIds.forEach(value => { - valueNew.add(value); - }) - let oldInstances = (this.observeAttrTelemetryFormGroup.get('clientLwM2M').value as ObjectLwM2M []).find(e => e.id == data.objectId).instances; - oldInstances.forEach(inst => { - valueOld.add(inst.id); + private updateInstancesIds = (data: Lwm2mObjectAddInstancesData): void => { + const objectLwM2MFormGroup = (this.observeAttrTelemetryFormGroup.get('clientLwM2M') as FormArray).controls + .find(e => e.value.id === data.objectId) as FormGroup; + const instancesArray = objectLwM2MFormGroup.value.instances as Instance []; + const instancesFormArray = objectLwM2MFormGroup.get('instances') as FormArray; + const instance0 = deepClone(instancesFormArray.at(0).value as Instance); + instance0.resources.forEach(r => { + r.attribute = false; + r.telemetry = false; + r.observe = false; }); - if (JSON.stringify(Array.from(valueOld)) != JSON.stringify(Array.from(valueNew))) { - let idsDel = this.diffBetweenSet(valueNew, this.deepCloneSet(valueOld)); - let idsAdd = this.diffBetweenSet(valueOld, this.deepCloneSet(valueNew)); + const valueOld = this.instancesToSetId(instancesArray); + if (!isEqual(valueOld, data.instancesIds)) { + const idsDel = this.diffBetweenSet(valueOld, data.instancesIds); + const idsAdd = this.diffBetweenSet(data.instancesIds, valueOld); if (idsAdd.size) { - this.addInstancesNew(data.objectId, idsAdd) + this.addInstancesNew(idsAdd, objectLwM2MFormGroup, instancesFormArray, instance0); } if (idsDel.size) { - this.delInstances(data.objectId, idsDel); + this.deleteInstances(idsDel, objectLwM2MFormGroup, instancesFormArray, instance0); } } } - delInstances(objectId: number, idsDel: Set): void { - let isIdIndex = (element) => element.id == objectId; - let objectIndex = (this.observeAttrTelemetryFormGroup.get('clientLwM2M').value as ObjectLwM2M []).findIndex(isIdIndex); - idsDel.forEach(x => { - isIdIndex = (element) => element.value.id == x; - let instancesFormArray = ((this.observeAttrTelemetryFormGroup.get('clientLwM2M') as FormArray).controls[objectIndex].get("instances") as FormArray); - let instanceIndex = instancesFormArray.controls.findIndex(isIdIndex); - instancesFormArray.removeAt(instanceIndex); - }) + private addInstancesNew = (idsAdd: Set, objectLwM2MFormGroup: FormGroup, instancesFormArray: FormArray, + instanceNew: Instance): void => { + idsAdd.forEach(x => { + this.pushInstance(instancesFormArray, x, instanceNew); + }); + (instancesFormArray.controls as FormGroup[]).sort((a, b) => a.value.id - b.value.id); } - addInstancesNew(objectId: number, idsAdd: Set): void { - let instancesValue = (this.observeAttrTelemetryFormGroup.get('clientLwM2M').value as ObjectLwM2M []).find(e => e.id == objectId).instances; - let instancesFormArray = ((this.observeAttrTelemetryFormGroup.get('clientLwM2M') as FormArray).controls.find(e => e.value.id == objectId).get("instances") as FormArray) as FormArray; - idsAdd.forEach(x => { - let instanceNew = deepClone(instancesValue[0]) as Instance; - instanceNew.id = x; - instanceNew.resources.forEach(r => { - r.attribute = false; - r.telemetry = false; - r.observe = false; - }); - instancesFormArray.push(this.fb.group({ - id: x, - [this.observe]: {value: false, disabled: this.disabled}, - [this.attribute]: {value: false, disabled: this.disabled}, - [this.telemetry]: {value: false, disabled: this.disabled}, - resources: {value: instanceNew.resources, disabled: this.disabled} - })); + private deleteInstances = (idsDel: Set, objectLwM2MFormGroup: FormGroup, instancesFormArray: FormArray, + instance0: Instance): void => { + idsDel.forEach(x => { + const instanceIndex = instancesFormArray.value.findIndex(element => element.id === x); + instancesFormArray.removeAt(instanceIndex); }); - (instancesFormArray.controls as FormGroup[]).sort((a,b) => a.value.id - b.value.id); + if (instancesFormArray.length === 0) { + this.pushInstance(instancesFormArray, 0, instance0); + } + (instancesFormArray.controls as FormGroup[]).sort((a, b) => a.value.id - b.value.id); } - deepCloneSet(oldSet: Set): Set { - let newSet = new Set(); - oldSet.forEach(p => { - newSet.add(p); - }) - return newSet; + private pushInstance = (instancesFormArray: FormArray, x: number, instanceNew: Instance): void => { + instancesFormArray.push(this.fb.group({ + id: x, + resources: {value: instanceNew.resources, disabled: this.disabled} + })); } - diffBetweenSet(firstSet: Set, secondSet: Set): Set { - firstSet.forEach(p => { - secondSet.delete(p); - }) - return secondSet + private diffBetweenSet(firstSet: Set, secondSet: Set): Set { + return new Set([...Array.from(firstSet)].filter(x => !secondSet.has(x))); } - setInstancesIds(instances: Instance []): Set { - let instancesIds = new Set(); - if (instances && instances.length) { - instances.forEach(inst => { - instancesIds.add(inst.id); - }); - } - return instancesIds; + private instancesToSetId = (instances: Instance[]): Set => { + return new Set(instances.map(x => x.id)); } } diff --git a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/profile-config.models.ts b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/profile-config.models.ts index c626138828..11c16ac802 100644 --- a/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/profile-config.models.ts +++ b/ui-ngx/src/app/modules/home/components/profile/device/lwm2m/profile-config.models.ts @@ -14,8 +14,6 @@ /// limitations under the License. /// -import { AbstractControl, ValidationErrors } from '@angular/forms'; - export const OBSERVE_ATTR = 'observeAttr'; export const OBSERVE = 'observe'; export const ATTR = 'attribute'; @@ -23,37 +21,29 @@ export const TELEMETRY = 'telemetry'; export const KEY_NAME = 'keyName'; export const DEFAULT_ID_SERVER = 123; export const DEFAULT_ID_BOOTSTRAP = 111; -export const DEFAULT_HOST_NAME = "localhost"; +export const DEFAULT_HOST_NAME = 'localhost'; export const DEFAULT_PORT_SERVER_NO_SEC = 5685; -export const DEFAULT_PORT_SERVER_SEC = 5686; -export const DEFAULT_PORT_SERVER_SEC_CERT = 5688; -export const DEFAULT_PORT_BOOTSTRAP_NO_SEC = 5689; -export const DEFAULT_PORT_BOOTSTRAP_SEC = 5690; -export const DEFAULT_PORT_BOOTSTRAP_SEC_CERT = 5692; +export const DEFAULT_PORT_BOOTSTRAP_NO_SEC = 5691; export const DEFAULT_CLIENT_HOLD_OFF_TIME = 1; export const DEFAULT_LIFE_TIME = 300; -export const DEFAULT_DEFAULT_MIN_PERIOD = 1; +export const DEFAULT_MIN_PERIOD = 1; export const DEFAULT_NOTIF_IF_DESIBLED = true; -export const DEFAULT_BINDING = "U"; +export const DEFAULT_BINDING = 'U'; export const DEFAULT_BOOTSTRAP_SERVER_ACCOUNT_TIME_OUT = 0; -export const LEN_MAX_PUBLIC_KEY_PSK = 182; -export const LEN_MAX_PUBLIC_KEY_RPK_X509 = 3000; -export const KEY_IDENT_REGEXP_PSK = /^[0-9a-fA-F]{64,64}$/; -export const KEY_PRIVATE_REGEXP = /^[0-9a-fA-F]{134,134}$/; -export const KEY_PUBLIC_REGEXP_PSK = /^[0-9a-fA-F]{182,182}$/; -export const KEY_PUBLIC_REGEXP_X509 = /^[0-9a-fA-F]{0,3000}$/; -export const CAMEL_CASE_REGEXP = /[-_&@.,*+!?^${}()|[\]\\]/g; +export const LEN_MAX_PUBLIC_KEY_RPK = 182; +export const LEN_MAX_PUBLIC_KEY_X509 = 3000; +export const KEY_REGEXP_HEX_DEC = /^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/; +export const KEY_REGEXP_NUMBER = /^(\-?|\+?)\d*$/; export const INSTANCES_ID_VALUE_MIN = 0; export const INSTANCES_ID_VALUE_MAX = 65535; -//ok export enum SECURITY_CONFIG_MODE { PSK = 'PSK', RPK = 'RPK', X509 = 'X509', NO_SEC = 'NO_SEC' } -//ok + export const SECURITY_CONFIG_MODE_NAMES = new Map( [ [SECURITY_CONFIG_MODE.PSK, 'Pre-Shared Key'], @@ -62,103 +52,88 @@ export const SECURITY_CONFIG_MODE_NAMES = new Map( [SECURITY_CONFIG_MODE.NO_SEC, 'No Security'], ] ); -//ok + export interface BootstrapServersSecurityConfig { - shortId: number, - lifetime: number, - defaultMinPeriod: number, - notifIfDisabled: boolean, - binding: string + shortId: number; + lifetime: number; + defaultMinPeriod: number; + notifIfDisabled: boolean; + binding: string; } -//ok export interface ServerSecurityConfig { - host?: string, - port?: number, - bootstrapServerIs?: boolean, - securityMode: string, - clientPublicKeyOrId?: string, - clientSecretKey?: string, + host?: string; + port?: number; + bootstrapServerIs?: boolean; + securityMode: string; + clientPublicKeyOrId?: string; + clientSecretKey?: string; serverPublicKey?: string; - clientHoldOffTime?: number, - serverId?: number, - bootstrapServerAccountTimeout: number + clientHoldOffTime?: number; + serverId?: number; + bootstrapServerAccountTimeout: number; } -//ok interface BootstrapSecurityConfig { - servers: BootstrapServersSecurityConfig, - bootstrapServer: ServerSecurityConfig, - lwm2mServer: ServerSecurityConfig + servers: BootstrapServersSecurityConfig; + bootstrapServer: ServerSecurityConfig; + lwm2mServer: ServerSecurityConfig; } -//ok export interface ProfileConfigModels { - bootstrap: BootstrapSecurityConfig, - observeAttr: { - observe: string [], - attribute: string [], - telemetry: string [], - keyName: [] - } + bootstrap: BootstrapSecurityConfig; + observeAttr: ObservableAttributes; +} + +export interface ObservableAttributes { + observe: string[]; + attribute: string[]; + telemetry: string[]; + keyName: string[]; } -//ok export function getDefaultBootstrapServersSecurityConfig(): BootstrapServersSecurityConfig { return { shortId: DEFAULT_ID_SERVER, lifetime: DEFAULT_LIFE_TIME, - defaultMinPeriod: DEFAULT_DEFAULT_MIN_PERIOD, + defaultMinPeriod: DEFAULT_MIN_PERIOD, notifIfDisabled: DEFAULT_NOTIF_IF_DESIBLED, binding: DEFAULT_BINDING - } + }; } -//ok export function getDefaultBootstrapServerSecurityConfig(hostname: any): ServerSecurityConfig { return { host: hostname, - port: getDefaultPortBootstrap(), + port: DEFAULT_PORT_BOOTSTRAP_NO_SEC, bootstrapServerIs: true, securityMode: SECURITY_CONFIG_MODE.NO_SEC.toString(), serverPublicKey: '', clientHoldOffTime: DEFAULT_CLIENT_HOLD_OFF_TIME, serverId: DEFAULT_ID_BOOTSTRAP, bootstrapServerAccountTimeout: DEFAULT_BOOTSTRAP_SERVER_ACCOUNT_TIME_OUT - } + }; } -//ok + export function getDefaultLwM2MServerSecurityConfig(hostname): ServerSecurityConfig { const DefaultLwM2MServerSecurityConfig = getDefaultBootstrapServerSecurityConfig(hostname); DefaultLwM2MServerSecurityConfig.bootstrapServerIs = false; - DefaultLwM2MServerSecurityConfig.port = getDefaultPortServer(); + DefaultLwM2MServerSecurityConfig.port = DEFAULT_PORT_SERVER_NO_SEC; DefaultLwM2MServerSecurityConfig.serverId = DEFAULT_ID_SERVER; return DefaultLwM2MServerSecurityConfig; } -//ok -export function getDefaultPortBootstrap(securityMode?: string): number { - return (!securityMode || securityMode === SECURITY_CONFIG_MODE.NO_SEC.toString()) ? DEFAULT_PORT_BOOTSTRAP_NO_SEC : - (securityMode === SECURITY_CONFIG_MODE.X509.toString()) ? DEFAULT_PORT_BOOTSTRAP_SEC_CERT : DEFAULT_PORT_BOOTSTRAP_SEC; -} -//ok -export function getDefaultPortServer(securityMode?: string): number { - return (!securityMode || securityMode === SECURITY_CONFIG_MODE.NO_SEC.toString()) ? DEFAULT_PORT_SERVER_NO_SEC : - (securityMode === SECURITY_CONFIG_MODE.X509.toString()) ? DEFAULT_PORT_SERVER_SEC_CERT : DEFAULT_PORT_SERVER_SEC; -} -//ok function getDefaultProfileBootstrapSecurityConfig(hostname: any): BootstrapSecurityConfig { return { servers: getDefaultBootstrapServersSecurityConfig(), bootstrapServer: getDefaultBootstrapServerSecurityConfig(hostname), lwm2mServer: getDefaultLwM2MServerSecurityConfig(hostname) - } + }; } -//ok export function getDefaultProfileConfig(hostname?: any): ProfileConfigModels { return { - bootstrap: getDefaultProfileBootstrapSecurityConfig((hostname)? hostname : DEFAULT_HOST_NAME), + bootstrap: getDefaultProfileBootstrapSecurityConfig((hostname) ? hostname : DEFAULT_HOST_NAME), observeAttr: { observe: [], attribute: [], @@ -168,19 +143,18 @@ export function getDefaultProfileConfig(hostname?: any): ProfileConfigModels { }; } -//ok export interface ResourceLwM2M { - id: number, - name: string, - observe: boolean, - attribute: boolean, - telemetry: boolean, - keyName: string + id: number; + name: string; + observe: boolean; + attribute: boolean; + telemetry: boolean; + keyName: string; } -//ok + export interface Instance { - id: number, - resources: ResourceLwM2M[] + id: number; + resources: ResourceLwM2M[]; } /** @@ -190,23 +164,10 @@ export interface Instance { * mandatory == false => Optional */ export interface ObjectLwM2M { - id: number, - name: string, - multiple?: boolean, - mandatory?: boolean, - instances?: Instance [] -} - -export function getChangeInstancesIds (): ChangeInstancesIds { - let changeInstancesIds: ChangeInstancesIds; - changeInstancesIds.add = new Set(); - changeInstancesIds.del = new Set(); - return changeInstancesIds; - -} - -export interface ChangeInstancesIds { - add: Set, - del: Set + id: number; + name: string; + multiple?: boolean; + mandatory?: boolean; + instances?: Instance []; } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/gateway/gateway-form.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/gateway/gateway-form.component.html index 19f6b87471..8340857d8d 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/gateway/gateway-form.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/gateway/gateway-form.component.html @@ -35,7 +35,7 @@ required > -
profile-tab +
{{'gateway.security-type' | translate }} diff --git a/ui-ngx/src/app/modules/home/pages/device/device.module.ts b/ui-ngx/src/app/modules/home/pages/device/device.module.ts index 54c02f447b..8ecdb6cb6a 100644 --- a/ui-ngx/src/app/modules/home/pages/device/device.module.ts +++ b/ui-ngx/src/app/modules/home/pages/device/device.module.ts @@ -25,8 +25,7 @@ import { HomeDialogsModule } from '../../dialogs/home-dialogs.module'; import { HomeComponentsModule } from '@modules/home/components/home-components.module'; import { DeviceTabsComponent } from '@home/pages/device/device-tabs.component'; import { SecurityConfigComponent } from '@home/pages/device/lwm2m/security-config.component'; -// TODO: @nickAS21 move to device profile -import {SecurityConfigServerComponent} from "@home/pages/device/lwm2m/security-config-server.component"; +import { SecurityConfigServerComponent } from '@home/pages/device/lwm2m/security-config-server.component'; import { DefaultDeviceConfigurationComponent } from './data/default-device-configuration.component'; import { DeviceConfigurationComponent } from './data/device-configuration.component'; import { DeviceDataComponent } from './data/device-data.component'; diff --git a/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config-server.component.html b/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config-server.component.html index a2be8e6334..9a5d2738ba 100644 --- a/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config-server.component.html +++ b/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config-server.component.html @@ -24,7 +24,7 @@ + [value]="securityMode"> {{ credentialTypeLwM2MNamesMap.get(securityConfigLwM2MType[securityMode]) }} @@ -35,43 +35,64 @@
{{ 'device.lwm2m-security-config.client-publicKey-or-id' | translate }} - + {{clientPublicKeyOrId.value?.length || 0}}/{{lenMaxClientPublicKeyOrId}} {{ 'device.lwm2m-security-config.client-publicKey-or-id' | translate }} {{ 'device.lwm2m-security-config.required' | translate }} - + {{ 'device.lwm2m-security-config.client-key' | translate }} - {{ 'device.lwm2m-security-config.pattern_hex_dec_182' | translate }} + {{ translate.get('device.lwm2m-security-config.pattern_hex_dec', { + count: 0 + }) | async }} - + {{ 'device.lwm2m-security-config.client-key' | translate }} - {{ 'device.lwm2m-security-config.pattern_hex_dec' | translate }} + {{ translate.get('device.lwm2m-security-config.pattern_hex_dec', { + count: lenMaxClientPublicKeyOrId + }) | async }} {{ 'device.lwm2m-security-config.client-secret-key' | translate }} - + {{clientSecretKey.value?.length || 0}}/{{lenMaxClientSecretKey}} {{ 'device.lwm2m-security-config.client-secret-key' | translate }} {{ 'device.lwm2m-security-config.required' | translate }} - + {{ 'device.lwm2m-security-config.client-key' | translate }} - {{ 'device.lwm2m-security-config.pattern_hex_dec_134' | translate }} + {{ translate.get('device.lwm2m-security-config.pattern_hex_dec', { + count: 0 + }) | async }} - + {{ 'device.lwm2m-security-config.client-key' | translate }} - {{ 'device-profile.lwm2m.pattern_hex_dec_64' | translate }} + {{ translate.get('device.lwm2m-security-config.pattern_hex_dec', { + count: lenMaxClientSecretKey + }) | async }}
diff --git a/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config-server.component.ts b/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config-server.component.ts index d60ff447c6..d88115e266 100644 --- a/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config-server.component.ts +++ b/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config-server.component.ts @@ -14,26 +14,23 @@ /// limitations under the License. /// -import {Component, forwardRef, Inject, Input, OnInit, ViewChild} from "@angular/core"; - -import { - ControlValueAccessor, - FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators -} from "@angular/forms"; +import { Component, forwardRef, Inject, Input, OnInit } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; import { - SECURITY_CONFIG_MODE, - SECURITY_CONFIG_MODE_NAMES, - KEY_IDENT_REGEXP_PSK, - ServerSecurityConfig, DeviceCredentialsDialogLwm2mData, + KEY_REGEXP_HEX_DEC, + LEN_MAX_PRIVATE_KEY, LEN_MAX_PSK, - LEN_MAX_PRIVATE_KEY, LEN_MAX_PUBLIC_KEY_RPK, KEY_PRIVATE_REGEXP, LEN_MAX_PUBLIC_KEY_X509, KEY_PUBLIC_REGEXP_X509 -} from "@home/pages/device/lwm2m/security-config.models"; -import {Store} from "@ngrx/store"; -import {AppState} from "@core/core.state"; -import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog"; -import {PageComponent} from "@shared/components/page.component"; -import {MatPaginator} from "@angular/material/paginator"; + LEN_MAX_PUBLIC_KEY_RPK, + LEN_MAX_PUBLIC_KEY_X509, + SECURITY_CONFIG_MODE, + SECURITY_CONFIG_MODE_NAMES, + ServerSecurityConfig +} from '@home/pages/device/lwm2m/security-config.models'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { PageComponent } from '@shared/components/page.component'; import { TranslateService } from '@ngx-translate/core'; @Component({ @@ -54,13 +51,13 @@ export class SecurityConfigServerComponent extends PageComponent implements OnIn securityConfigLwM2MType = SECURITY_CONFIG_MODE; securityConfigLwM2MTypes = Object.keys(SECURITY_CONFIG_MODE); credentialTypeLwM2MNamesMap = SECURITY_CONFIG_MODE_NAMES; - lenMaxClientPublicKeyOrId = LEN_MAX_PSK; + lenMinClientPublicKeyOrId = 0; + lenMaxClientPublicKeyOrId = LEN_MAX_PUBLIC_KEY_RPK; + lenMinClientSecretKey = LEN_MAX_PRIVATE_KEY; lenMaxClientSecretKey = LEN_MAX_PRIVATE_KEY; @Input() serverFormGroup: FormGroup; - @ViewChild(MatPaginator) paginator: MatPaginator; - constructor(protected store: Store, @Inject(MAT_DIALOG_DATA) public data: DeviceCredentialsDialogLwm2mData, public dialogRef: MatDialogRef, @@ -73,40 +70,59 @@ export class SecurityConfigServerComponent extends PageComponent implements OnIn this.registerDisableOnLoadFormControl(this.serverFormGroup.get('securityMode')); } - updateValueFields(serverData: ServerSecurityConfig): void { + private updateValueFields(serverData: ServerSecurityConfig): void { this.serverFormGroup.patchValue(serverData, {emitEvent: false}); const securityMode = this.serverFormGroup.get('securityMode').value as SECURITY_CONFIG_MODE; this.updateValidate(securityMode); } - updateValidate(securityMode: SECURITY_CONFIG_MODE): void { + private updateValidate(securityMode: SECURITY_CONFIG_MODE): void { switch (securityMode) { case SECURITY_CONFIG_MODE.NO_SEC: this.serverFormGroup.get('clientPublicKeyOrId').setValidators([]); this.serverFormGroup.get('clientSecretKey').setValidators([]); break; case SECURITY_CONFIG_MODE.PSK: + this.lenMinClientPublicKeyOrId = 0; this.lenMaxClientPublicKeyOrId = LEN_MAX_PUBLIC_KEY_RPK; + this.lenMinClientSecretKey = LEN_MAX_PSK; this.lenMaxClientSecretKey = LEN_MAX_PSK; - this.serverFormGroup.get('clientPublicKeyOrId').setValidators([Validators.required]); - this.serverFormGroup.get('clientSecretKey').setValidators([Validators.required, Validators.pattern(KEY_IDENT_REGEXP_PSK)]); + this.setValidatorsSecurity(securityMode); break; case SECURITY_CONFIG_MODE.RPK: - this.lenMaxClientPublicKeyOrId = LEN_MAX_PUBLIC_KEY_X509; + this.lenMinClientPublicKeyOrId = LEN_MAX_PUBLIC_KEY_RPK; + this.lenMaxClientPublicKeyOrId = LEN_MAX_PUBLIC_KEY_RPK; + this.lenMinClientSecretKey = LEN_MAX_PRIVATE_KEY; this.lenMaxClientSecretKey = LEN_MAX_PRIVATE_KEY; - this.serverFormGroup.get('clientPublicKeyOrId').setValidators([Validators.required, Validators.pattern(KEY_PUBLIC_REGEXP_X509)]); - this.serverFormGroup.get('clientSecretKey').setValidators([Validators.required, Validators.pattern(KEY_PRIVATE_REGEXP)]); + this.setValidatorsSecurity(securityMode); break; case SECURITY_CONFIG_MODE.X509: + this.lenMinClientPublicKeyOrId = 0; this.lenMaxClientPublicKeyOrId = LEN_MAX_PUBLIC_KEY_X509; + this.lenMinClientSecretKey = LEN_MAX_PRIVATE_KEY; this.lenMaxClientSecretKey = LEN_MAX_PRIVATE_KEY; - this.serverFormGroup.get('clientPublicKeyOrId').setValidators([Validators.required, Validators.pattern(KEY_PUBLIC_REGEXP_X509)]); - this.serverFormGroup.get('clientSecretKey').setValidators([Validators.required, Validators.pattern(KEY_PRIVATE_REGEXP)]); + this.setValidatorsSecurity(securityMode); break; } this.serverFormGroup.updateValueAndValidity(); } + private setValidatorsSecurity = (securityMode: SECURITY_CONFIG_MODE): void => { + if (securityMode === SECURITY_CONFIG_MODE.PSK) { + this.serverFormGroup.get('clientPublicKeyOrId').setValidators([Validators.required]); + } else { + this.serverFormGroup.get('clientPublicKeyOrId').setValidators([Validators.required, + Validators.pattern(KEY_REGEXP_HEX_DEC), + Validators.minLength(this.lenMinClientPublicKeyOrId), + Validators.maxLength(this.lenMaxClientPublicKeyOrId)]); + } + + this.serverFormGroup.get('clientSecretKey').setValidators([Validators.required, + Validators.pattern(KEY_REGEXP_HEX_DEC), + Validators.minLength(this.lenMinClientSecretKey), + Validators.maxLength(this.lenMaxClientSecretKey)]); + } + securityModeChanged(securityMode: SECURITY_CONFIG_MODE): void { this.updateValidate(securityMode); } diff --git a/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config.component.html b/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config.component.html index 20b163503c..e2b95cdb73 100644 --- a/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config.component.html +++ b/ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config.component.html @@ -35,110 +35,130 @@ {{ 'device.lwm2m-security-config.required' | translate }}
- + -
- - device.lwm2m-security-config.mode - - - {{ credentialTypeLwM2MNamesMap.get(securityConfigLwM2MType[securityConfigClientMode]) }} - - - -
+ +
- {{ 'device.lwm2m-security-config.identity' | translate }} - - - {{ 'device.lwm2m-security-config.identity' | translate }} - {{ 'device.lwm2m-security-config.required' | translate }} - + device.lwm2m-security-config.mode + + + {{ credentialTypeLwM2MNamesMap.get(securityConfigLwM2MType[securityConfigClientMode]) }} + + -
-
+ + {{ 'device.lwm2m-security-config.identity' | translate }} + + + {{ 'device.lwm2m-security-config.identity' | translate }} + {{ 'device.lwm2m-security-config.required' | translate }} + + +
+
- - {{ 'device.lwm2m-security-config.client-key' | translate }} - - {{clientKey.value?.length || 0}}/{{lenMaxKeyClient}} - - {{ 'device.lwm2m-security-config.client-key' | translate }} - {{ 'device.lwm2m-security-config.required' | translate }} - - - {{ 'device.lwm2m-security-config.client-key' | translate }} - {{ 'device-profile.lwm2m-security-config.pattern_hex_dec_64' | translate }} - - - {{ 'device.lwm2m-security-config.client-key' | translate }} - {{ 'device.lwm2m-security-config.pattern_hex_dec_182' | translate }} - - -
-
- - {{ 'device.lwm2m-security-config.client-certificate' | translate }} - + + {{ 'device.lwm2m-security-config.client-key' | translate }} + + {{clientKey.value?.length || 0}}/{{lenMaxKeyClient}} + + {{ 'device.lwm2m-security-config.client-key' | translate }} + {{ 'device.lwm2m-security-config.required' | translate }} + + + {{ 'device.lwm2m-security-config.client-key' | translate }} + {{ translate.get('device.lwm2m-security-config.pattern_hex_dec', { + count: 0 + }) | async }} + + + {{ 'device.lwm2m-security-config.client-key' | translate }} + {{ translate.get('device.lwm2m-security-config.pattern_hex_dec', { + count: lenMaxKeyClient + }) | async }} + + +
+
+ + {{ 'device.lwm2m-security-config.client-certificate' | translate }} + +
-
+
-
- - - - -
{{ 'device.lwm2m-security-config.bootstrap-server' | translate | uppercase }}
-
-
-
- - -
-
-
- - - - -
{{ 'device.lwm2m-security-config.lwm2m-server' | translate | uppercase }}
-
-
-
- - -
-
-
-
+ +
+ + + + +
{{ 'device.lwm2m-security-config.bootstrap-server' | translate | uppercase }}
+
+
+ +
+ + +
+
+
+
+ + + + +
{{ 'device.lwm2m-security-config.lwm2m-server' | translate | uppercase }}
+
+
+ +
+ + +
+
+
+
+
+
-
-
- - -
-
+ +
+
+ + +
+
+
@@ -148,7 +168,7 @@