Browse Source

Merge remote-tracking branch 'upstream/develop/3.3' into develop/3.3-edge

pull/3811/head
Volodymyr Babak 6 years ago
parent
commit
499eb1aef4
  1. 1
      application/src/main/java/org/thingsboard/server/controller/DeviceController.java
  2. 68
      application/src/main/java/org/thingsboard/server/controller/DeviceLwm2mController.java
  3. 124
      application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MModelsRepository.java
  4. 14
      application/src/main/java/org/thingsboard/server/service/transport/DefaultTransportApiService.java
  5. 52
      application/src/main/resources/thingsboard.yml
  6. 6
      common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceService.java
  7. 12
      common/data/src/main/java/org/thingsboard/server/common/data/Device.java
  8. 2
      common/data/src/main/java/org/thingsboard/server/common/data/security/DeviceCredentialsType.java
  9. 1
      common/queue/src/main/proto/queue.proto
  10. 23
      common/transport/lwm2m/pom.xml
  11. 225
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/LwM2MTransportBootstrapServerConfiguration.java
  12. 43
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/LwM2MTransportBootstrapServerInitializer.java
  13. 84
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapSecurityStore.java
  14. 205
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MSetSecurityStoreBootstrap.java
  15. 1
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2mDefaultBootstrapSessionManager.java
  16. 6
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LWM2MGenerationPSkRPkECC.java
  17. 49
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LwM2mCredentialsSecurityInfoValidator.java
  18. 6
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MSessionMsgListener.java
  19. 88
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportContextServer.java
  20. 207
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportHandler.java
  21. 203
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportRequest.java
  22. 280
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServerConfiguration.java
  23. 73
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServerInitializer.java
  24. 969
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportService.java
  25. 1159
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServiceImpl.java
  26. 22
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2mServerListener.java
  27. 38
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/ResultIds.java
  28. 39
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/adaptors/LwM2MJsonAdaptor.java
  29. 4
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/adaptors/LwM2MTransportAdaptor.java
  30. 70
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/LwM2MClient.java
  31. 6
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/ModelObject.java
  32. 14
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/client/ResourceValue.java
  33. 234
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/secure/LwM2MSetSecurityStoreServer.java
  34. 136
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/secure/LwM2mInMemorySecurityStore.java
  35. 13
      common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/utils/LwM2mValueConverterImpl.java
  36. BIN
      common/transport/lwm2m/src/main/resources/credentials/serverKeyStore.jks
  37. 309
      common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_credentials.sh
  38. 19
      common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_keygen.properties
  39. 208
      common/transport/lwm2m/src/main/resources/models/LWM2M_Connectivity_Monitoring-v1_0_2.xml
  40. 147
      common/transport/lwm2m/src/main/resources/models/LwM2M_BinaryAppDataContainer-v1_0_1.xml
  41. 10
      common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/MqttTransportHandler.java
  42. 5
      common/transport/transport-api/pom.xml
  43. 2
      common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/TransportContext.java
  44. 8
      common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/TransportService.java
  45. 3
      common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/adaptor/JsonConverter.java
  46. 5
      common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/auth/SessionInfoCreator.java
  47. 53
      common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/lwm2m/LwM2MTransportConfigBootstrap.java
  48. 134
      common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/lwm2m/LwM2MTransportConfigServer.java
  49. 27
      common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/DefaultTransportService.java
  50. 3
      common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/SessionMetaData.java
  51. 4
      dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java
  52. 9
      dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsServiceImpl.java
  53. 47
      dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java
  54. 1
      dao/src/main/java/org/thingsboard/server/dao/user/UserServiceImpl.java
  55. 7
      netty-mqtt/pom.xml
  56. 28
      pom.xml
  57. 19
      rest-client/src/main/java/org/thingsboard/rest/client/RestClient.java
  58. 26
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/AnonymousCredentials.java
  59. 24
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/BasicCredentials.java
  60. 35
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/CertPemCredentials.java
  61. 26
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/ClientCredentials.java
  62. 17
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/CredentialsType.java
  63. 42
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/TbMqttNode.java
  64. 6
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/TbMqttNodeConfiguration.java
  65. 42
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/azure/AzureIotHubSasCredentials.java
  66. 55
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/azure/TbAzureIotHubNode.java
  67. 3
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/azure/TbAzureIotHubNodeConfiguration.java
  68. 42
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/credentials/BasicCredentials.java
  69. 7
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/profile/AlarmState.java
  70. 12
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/profile/DeviceState.java
  71. 21
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbHttpClient.java
  72. 4
      rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbRestApiCallNodeConfiguration.java
  73. 2
      rule-engine/rule-engine-components/src/main/resources/public/static/rulenode/rulenode-core-config.js
  74. 60
      transport/lwm2m/pom.xml
  75. BIN
      transport/lwm2m/src/main/data/credentials/serverKeyStore.jks
  76. 403
      transport/lwm2m/src/main/data/credentials/shell/lwM2M_credentials.sh
  77. 57
      transport/lwm2m/src/main/data/credentials/shell/lwM2M_keygen.properties
  78. 167
      transport/lwm2m/src/main/data/models/LWM2M_Connectivity_Monitoring-v1_0_2.xml
  79. 164
      transport/lwm2m/src/main/data/models/LwM2M_BinaryAppDataContainer-v1_0_1.xml
  80. 51
      transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml
  81. 5
      ui-ngx/angular.json
  82. 2
      ui-ngx/src/app/core/api/widget-api.models.ts
  83. 35
      ui-ngx/src/app/core/http/device-profile.service.ts
  84. 2
      ui-ngx/src/app/modules/dashboard/dashboard-pages.module.ts
  85. 3
      ui-ngx/src/app/modules/dashboard/dashboard-pages.routing.module.ts
  86. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.html
  87. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.ts
  88. 8
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html
  89. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.scss
  90. 19
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts
  91. 1
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.models.ts
  92. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-settings-dialog.component.html
  93. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-settings-dialog.component.scss
  94. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-settings-dialog.component.ts
  95. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-toolbar.component.html
  96. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-toolbar.component.scss
  97. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-toolbar.component.ts
  98. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html
  99. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.scss
  100. 0
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts

1
application/src/main/java/org/thingsboard/server/controller/DeviceController.java

@ -300,7 +300,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);
sendEntityNotificationMsg(getTenantId(), device.getId(), EdgeEventActionType.CREDENTIALS_UPDATED);

68
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<LwM2mObject> getLwm2mListObjects(@PathVariable("objectIds") int[] objectIds) throws ThingsboardException {
public List<LwM2mObject> 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<LwM2mObject> 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<Class<?>, 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);
}
}
}

124
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<ObjectModel>)
*/
public List<LwM2mObject> 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<LwM2mObject> 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<LwM2mObject> getLwm2mObjects(Predicate<? super ObjectModel> predicate) {
private List<LwM2mObject> getLwm2mObjects(Predicate<? super ObjectModel> predicate, String sortProperty, String sortOrder) {
List<LwM2mObject> lwM2mObjects = new ArrayList<>();
List<ObjectModel> 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<LwM2mObject> sortList (List<LwM2mObject> 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<LwM2mObject>.size()
*/
public PageData<LwM2mObject> 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) {

14
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;
}

52
application/src/main/resources/thingsboard.yml

@ -584,7 +584,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
@ -597,24 +603,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}"
@ -624,23 +625,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:''}"
# Edges parameters

6
common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceService.java

@ -23,12 +23,12 @@ import org.thingsboard.server.common.data.EntitySubtype;
import org.thingsboard.server.common.data.device.DeviceSearchQuery;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.EdgeId;
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.page.TimePageLink;
import org.thingsboard.server.common.data.security.DeviceCredentials;
import org.thingsboard.server.dao.device.provision.ProvisionRequest;
import java.util.List;
@ -47,6 +47,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);

12
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<DeviceId> 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;
}

2
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
}

1
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 {

23
common/transport/lwm2m/pom.xml

@ -82,15 +82,10 @@
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<!-- lechan start -->
<dependency>
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-server-cf</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.eclipse.leshan</groupId>-->
<!-- <artifactId>leshan-server-cf</artifactId>-->
<!-- </dependency> -->
<dependency>
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-client-cf</artifactId>
@ -100,12 +95,6 @@
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-server-redis</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.eclipse.californium</groupId>-->
<!-- <artifactId>californium-core</artifactId>-->
<!-- </dependency>-->
<!-- leshan finish -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@ -124,14 +113,20 @@
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>californium-core</artifactId>
<version>${californium.version}</version>
<type>test-jar</type>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>californium-core</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.eclipse.californium</groupId>-->
<!-- <artifactId>scandium</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>element-connector</artifactId>
<version>${californium.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>

225
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);
}
}
}

43
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!");
}
}

84
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<SecurityInfo> 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()));
}
}

205
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MSetSecurityStoreBootstrap.java

@ -1,205 +0,0 @@
/**
* Copyright © 2016-2021 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();
// }
// }
}

1
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) {

6
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();

49
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/secure/LwM2MGetSecurityInfo.java → 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<DeviceProfile> 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);
}

6
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<Future<? super Void>>, 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

88
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 <T> TransportServiceCallback<Void> getPubAckCallbackSentAttrTelemetry(final T msg) {
return new TransportServiceCallback<Void>() {
@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();
}
}

207
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 <T> Optional<T> 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 <V>
* @return
*/
public static <V extends Comparable<V>> boolean mapsEquals(Map<?,V> map1, Map<?,V> map2) {
List<V> values1 = new ArrayList<V>(map1.values());
List<V> values2 = new ArrayList<V>(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<String> linkedListOut = new LinkedList<String>();
public static String splitCamelCaseString(String s) {
LinkedList<String> linkedListOut = new LinkedList<>();
LinkedList<String> linkedList = new LinkedList<String>((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 <T> TransportServiceCallback<Void> getAckCallback(LwM2MClient lwM2MClient, int requestId, String typeTopic) {
return new TransportServiceCallback<Void>() {
@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());
}
};
}
}

203
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<Registration> 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 <b>String Single-Instance Resource</b> 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 <b>String Single-Instance Resource</b> 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 <b>String Single-Instance Resource</b> 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);
}
}
}

280
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> 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);
}
}
}

73
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!");
}
}

969
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<Observation> previousObsersations);
@Autowired
private LwM2MJsonAdaptor adaptor;
void updatedReg(LeshanServer lwServer, Registration registration);
@Autowired
private TransportService transportService;
void unReg(LeshanServer lwServer, Registration registration, Collection<Observation> 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<String <registrationId >, 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<Observation> 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<DeviceProfile> 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<Observation> 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<UUID, AttrTelemetryObserveValue> 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<String> 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<String> 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 <T> TransportServiceCallback<Void> getPubAckCallbackSentAttrTelemetry(final int msgId, final T msg) {
return new TransportServiceCallback<Void>() {
@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<Observation> 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<Integer, ?> values, String path) {
ResultIds resultIds = new ResultIds(path);
// #1
LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getlwM2MClient(registration.getId());
ModelObject modelObject = lwM2MClient.getModelObjects().get(resultIds.getObjectId());
Map<Integer, LwM2mObjectInstance> instancesModelObject = modelObject.getInstances();
LwM2mObjectInstance instanceOld = (instancesModelObject.get(resultIds.instanceId) != null) ? instancesModelObject.get(resultIds.instanceId) : null;
Map<Integer, LwM2mResource> 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<Integer, LwM2mResource> 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<String> paths = new HashSet<String>();
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<Map.Entry<Integer, ResourceModel>> predicateRes = res -> keyName.equals(splitCamelCaseString(res.getValue().name));
Predicate<Map.Entry<Integer, ModelObject>> predicateObj = (obj -> {
return obj.getValue().getObjectModel().resources.entrySet().stream().filter(predicateRes).findFirst().isPresent();
});
Stream<Map.Entry<Integer, ModelObject>> objectStream = lwM2MClient.getModelObjects().entrySet().stream().filter(predicateObj);
Predicate<Map.Entry<Integer, ResourceModel>> predicateResFinal = (objectStream.count() > 0) ? predicateRes : res -> keyName.equals(res.getValue().name);
Predicate<Map.Entry<Integer, ModelObject>> predicateObjFinal = (obj -> {
return obj.getValue().getObjectModel().resources.entrySet().stream().filter(predicateResFinal).findFirst().isPresent();
});
Map.Entry<Integer, ModelObject> 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<DeviceProfile> deviceProfileOpt) {
Optional<String> 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<DeviceProfile> 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<String> attributeSetOld = new Gson().fromJson(attributeOld, Set.class);
JsonArray telemetryOld = attrTelemetryObserveValueOld.getPostTelemetryProfile();
Set<String> 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<String> attributeSetNew = new Gson().fromJson(attributeNew, Set.class);
JsonArray telemetryNew = attrTelemetryObserveValueNew.getPostTelemetryProfile();
Set<String> 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<String> observeSetOld = new Gson().fromJson(observeOld, Set.class);
Set<String> 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<String> parametersOld, Set<String> 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<String, String> keyNameOld, ConcurrentMap<String, String> keyNameNew) {
ResultsAnalyzerParameters analyzerParameters = new ResultsAnalyzerParameters();
Set<String> 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<String> parametersObserve, Set<String> 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<String> 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<String> 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<Integer, ?> 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);
}
}
}

1159
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2MTransportServiceImpl.java

File diff suppressed because it is too large

22
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<Observation> previousObsersations) {
service.onRegistered(lhServer, registration, previousObsersations);
Collection<Observation> previousObservations) {
service.onRegistered(lhServer, registration, previousObservations);
}
/**
@ -63,7 +63,7 @@ public class LwM2mServerListener {
@Override
public void unregistered(Registration registration, Collection<Observation> 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());
}
};
}

38
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/ResultIds.java

@ -1,38 +0,0 @@
/**
* Copyright © 2016-2021 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;
}
}
}

39
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<String> clientKeys, List<String> sharedKeys) throws AdaptorException {
return processGetAttributeRequestMsg(clientKeys, sharedKeys);
}
protected TransportProtos.GetAttributeRequestMsg processGetAttributeRequestMsg(List<String> clientKeys, List<String> 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<String> 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;
}
}
}

4
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<String> clientKeys, List<String> sharedKeys) throws AdaptorException;
}

70
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<String, String> attributes;
private Map<Integer, ModelObject> modelObjects;
private Map<String, ResourceValue> resources;
private Set<String> pendingRequests;
private Map<String, TransportProtos.TsKvProto> delayedRequests;
private Set<Integer> delayedRequestsId;
private Map<String, LwM2mResponse> responses;
private final LwM2mValueConverterImpl converter;
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public LwM2MClient(String endPoint, String identity, SecurityInfo info, ValidateDeviceCredentialsResponseMsg credentialsResponse, Map<String, String> attributes, Map<Integer, ModelObject> 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<String, String>();
this.modelObjects = (modelObjects != null && modelObjects.size() > 0) ? modelObjects : new ConcurrentHashMap<Integer, ModelObject>();
this.attributes = new ConcurrentHashMap<>();
this.pendingRequests = ConcurrentHashMap.newKeySet();
this.delayedRequests = new ConcurrentHashMap<>();
this.resources = new ConcurrentHashMap<>();
this.delayedRequestsId = ConcurrentHashMap.newKeySet();
this.profileUuid = profileUuid;
/**
* Key <objectId>, response<Value -> 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<ObjectModel>) 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<Integer, LwM2mObjectInstance> 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);
}
}
}

6
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();
}
}

14
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<Integer, ?> values;
Map<Integer, ?> values;
Object value;
boolean multiInstances;
public ResourceValue(Map<Integer, ?> values, Object value, boolean multiInstances) {
this.values = values;
this.value = value;
this.multiInstances = multiInstances;
}
public Object getResourceValue() {
return this.multiInstances ? this.values : this.value;
}
}

234
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/secure/LwM2MSetSecurityStoreServer.java

@ -1,234 +0,0 @@
/**
* Copyright © 2016-2021 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> 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).");
}
}
}

136
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<String /** registrationId */, LwM2MClient> sessions = new ConcurrentHashMap<>();
protected Map<UUID /** profileUUid */, AttrTelemetryObserveValue> profiles = new ConcurrentHashMap<>();
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();
private final Map<String /** registrationId */, LwM2MClient> sessions = new ConcurrentHashMap<>();
private Map<UUID /** profileUUid */, AttrTelemetryObserveValue> 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<SecurityInfo> 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<String, LwM2MClient> 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<String> 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<String, LwM2MClient> 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<String, LwM2MClient> 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<String, LwM2MClient> getSessions() {
@ -193,14 +232,14 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore {
return this.profiles;
}
public Map<UUID, AttrTelemetryObserveValue>setProfiles(Map<UUID, AttrTelemetryObserveValue> profiles) {
public AttrTelemetryObserveValue getProfile(UUID profileUuId) {
return this.profiles.get(profileUuId);
}
public Map<UUID, AttrTelemetryObserveValue> setProfiles(Map<UUID, AttrTelemetryObserveValue> 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);
}
}

13
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;
}

BIN
common/transport/lwm2m/src/main/resources/credentials/serverKeyStore.jks

Binary file not shown.

309
common/transport/lwm2m/src/main/resources/credentials/shell/lwM2M_credentials.sh

@ -1,4 +1,4 @@
#!/bin/sh
#!/bin/bash
#
# Copyright © 2016-2021 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}"

19
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"

208
common/transport/lwm2m/src/main/resources/models/LWM2M_Connectivity_Monitoring-v1_0_2.xml

@ -1,208 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
FILE INFORMATION
OMA Permanent Document
File: OMA-SUP-XML_LWM2M_Connectivity_Monitoring-V1_0_2-20180612-A
Type: xml
Date: 2018-June-12
Public Reachable Information
Path: http://www.openmobilealliance.org/tech/profiles
Name: LWM2M_Connectivity_Monitoring-v1_0_2.xml
NORMATIVE INFORMATION
Information about this file can be found in the latest revision of
OMA-TS-LightweightM2M-V1_0_2
OMA-TS-LightweightM2M_Core-V1_1
This is available at http://www.openmobilealliance.org/
Send comments to https://github.com/OpenMobileAlliance/OMA_LwM2M_for_Developers/issues
LEGAL DISCLAIMER
Copyright 2018 Open Mobile Alliance All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
The above license is used as a license under copyright only. Please
reference the OMA IPR Policy for patent licensing terms:
http://www.openmobilealliance.org/ipr.html
-->
<LWM2M xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://openmobilealliance.org/tech/profiles/LWM2M.xsd">
<Object ObjectType="MODefinition">
<Name>Connectivity Monitoring</Name>
<Description1>
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.
</Description1>
<ObjectID>4</ObjectID>
<ObjectURN>urn:oma:lwm2m:oma:4</ObjectURN>
<LWM2MVersion>1.0</LWM2MVersion>
<ObjectVersion>1.0</ObjectVersion>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Resources>
<Item ID="0">
<Name>Network Bearer</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Mandatory</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>0-50</RangeEnumeration>
<Units/>
<Description>
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.
</Description>
</Item>
<Item ID="1">
<Name>Available Network Bearer</Name>
<Operations>R</Operations>
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Mandatory</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>0-50</RangeEnumeration>
<Units/>
<Description>
Indicates a list of current available network bearer. Each Resource Instance has a value from the network bearer list.
</Description>
</Item>
<Item ID="2">
<Name>Radio Signal Strength</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Mandatory</Mandatory>
<Type>Integer</Type>
<RangeEnumeration/>
<Units>dBm</Units>
<Description>
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).
</Description>
</Item>
<Item ID="3">
<Name>Link Quality</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration/>
<Units/>
<Description>
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]).
</Description>
</Item>
<Item ID="4">
<Name>IP Addresses</Name>
<Operations>R</Operations>
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Mandatory</Mandatory>
<Type>String</Type>
<RangeEnumeration/>
<Units/>
<Description>
The IP addresses assigned to the connectivity interface. (e.g. IPv4, IPv6, etc.)
</Description>
</Item>
<Item ID="5">
<Name>Router IP Addresses</Name>
<Operations>R</Operations>
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>String</Type>
<RangeEnumeration/>
<Units/>
<Description>
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.
</Description>
</Item>
<Item ID="6">
<Name>Link Utilization</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>0-100</RangeEnumeration>
<Units>%</Units>
<Description>
The percentage indicating the average utilization of the link to the next-hop IP router.
</Description>
</Item>
<Item ID="7">
<Name>APN</Name>
<Operations>R</Operations>
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>String</Type>
<RangeEnumeration/>
<Units/>
<Description>
Access Point Name in case Network Bearer Resource is a Cellular Network.
</Description>
</Item>
<Item ID="8">
<Name>Cell ID</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration/>
<Units/>
<Description>
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].
</Description>
</Item>
<Item ID="9">
<Name>SMNC</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>0-999</RangeEnumeration>
<Units>%</Units>
<Description>
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].
</Description>
</Item>
<Item ID="10">
<Name>SMCC</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>0-999</RangeEnumeration>
<Units/>
<Description>
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].
</Description>
</Item>
</Resources>
<Description2/>
</Object>
</LWM2M>

147
common/transport/lwm2m/src/main/resources/models/LwM2M_BinaryAppDataContainer-v1_0_1.xml

@ -1,147 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
FILE INFORMATION
OMA Permanent Document
File: OMA-SUP-LwM2M_BinaryAppDataContainer-V1_0_1-20190221-A
Type: xml
Public Reachable Information
Path: http://www.openmobilealliance.org/tech/profiles
Name: LwM2M_BinaryAppDataContainer-v1_0_1.xml
NORMATIVE INFORMATION
Information about this file can be found in the latest revision of
OMA-TS-LWM2M_BinaryAppDataContainer-V1_0_1
This is available at http://www.openmobilealliance.org/
Send comments to https://github.com/OpenMobileAlliance/OMA_LwM2M_for_Developers/issues
CHANGE HISTORY
15062018 Status changed to Approved by DM, Doc Ref # OMA-DM&SE-2018-0061-INP_LWM2M_APPDATA_V1_0_ERP_for_final_Approval
21022019 Status changed to Approved by IPSO, Doc Ref # OMA-IPSO-2019-0025-INP_LwM2M_Object_App_Data_Container_1_0_1_for_Final_Approval
LEGAL DISCLAIMER
Copyright 2019 Open Mobile Alliance.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
The above license is used as a license under copyright only. Please
reference the OMA IPR Policy for patent licensing terms:
https://www.omaspecworks.org/about/intellectual-property-rights/
-->
<LWM2M xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://openmobilealliance.org/tech/profiles/LWM2M.xsd">
<Object ObjectType="MODefinition">
<Name>BinaryAppDataContainer</Name>
<Description1><![CDATA[This LwM2M Objects provides the application service data related to a LwM2M Server, eg. Water meter data.
There are several methods to create instance to indicate the message direction based on the negotiation between Application and LwM2M. The Client and Server should negotiate the instance(s) used to exchange the data. For example:
- Using a single instance for both directions communication, from Client to Server and from Server to Client.
- Using an instance for communication from Client to Server and another one for communication from Server to Client
- Using several instances
]]></Description1>
<ObjectID>19</ObjectID>
<ObjectURN>urn:oma:lwm2m:oma:19</ObjectURN>
<LWM2MVersion>1.0</LWM2MVersion>
<ObjectVersion>1.0</ObjectVersion>
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Resources>
<Item ID="0"><Name>Data</Name>
<Operations>RW</Operations>
<!-- <MultipleInstances>Single</MultipleInstances>-->
<!-- <Mandatory>Optional</Mandatory>-->
<!-- <Type>String</Type>-->
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Mandatory</Mandatory>
<Type>Opaque</Type>
<RangeEnumeration />
<Units />
<Description><![CDATA[Indicates the application data content.]]></Description>
</Item>
<Item ID="1"><Name>Data Priority</Name>
<Operations>RW</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>1 bytes</RangeEnumeration>
<Units />
<Description><![CDATA[Indicates the Application data priority:
0:Immediate
1:BestEffort
2:Latest
3-100: Reserved for future use.
101-254: Proprietary mode.]]></Description>
</Item>
<Item ID="2"><Name>Data Creation Time</Name>
<Operations>RW</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Time</Type>
<RangeEnumeration />
<Units />
<Description><![CDATA[Indicates the Data instance creation timestamp.]]></Description>
</Item>
<Item ID="3"><Name>Data Description</Name>
<Operations>RW</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>String</Type>
<RangeEnumeration>32 bytes</RangeEnumeration>
<Units />
<Description><![CDATA[Indicates the data description.
e.g. "meter reading".]]></Description>
</Item>
<Item ID="4"><Name>Data Format</Name>
<Operations>RW</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>String</Type>
<RangeEnumeration>32 bytes</RangeEnumeration>
<Units />
<Description><![CDATA[Indicates the format of the Application Data.
e.g. YG-Meter-Water-Reading
UTF8-string
]]></Description>
</Item>
<Item ID="5"><Name>App ID</Name>
<Operations>RW</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>2 bytes</RangeEnumeration>
<Units />
<Description><![CDATA[Indicates the destination Application ID.]]></Description>
</Item></Resources>
<Description2><![CDATA[]]></Description2>
</Object>
</LWM2M>

10
common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/MqttTransportHandler.java

@ -55,6 +55,7 @@ import org.thingsboard.server.common.transport.auth.SessionInfoCreator;
import org.thingsboard.server.common.transport.auth.TransportDeviceInfo;
import org.thingsboard.server.common.transport.auth.ValidateDeviceCredentialsResponse;
import org.thingsboard.server.common.transport.service.DefaultTransportService;
import org.thingsboard.server.common.transport.service.SessionMetaData;
import org.thingsboard.server.gen.transport.TransportProtos;
import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceResponseMsg;
import org.thingsboard.server.gen.transport.TransportProtos.SessionEvent;
@ -596,7 +597,7 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
}
}
private void checkGatewaySession() {
private void checkGatewaySession(SessionMetaData sessionMetaData) {
TransportDeviceInfo device = deviceSessionCtx.getDeviceInfo();
try {
JsonNode infoNode = context.getMapper().readTree(device.getAdditionalInfo());
@ -604,6 +605,9 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
JsonNode gatewayNode = infoNode.get("gateway");
if (gatewayNode != null && gatewayNode.asBoolean()) {
gatewaySessionHandler = new GatewaySessionHandler(deviceSessionCtx, sessionId);
if (infoNode.has(DefaultTransportService.OVERWRITE_ACTIVITY_TIME) && infoNode.get(DefaultTransportService.OVERWRITE_ACTIVITY_TIME).isBoolean()) {
sessionMetaData.setOverwriteActivityTime(infoNode.get(DefaultTransportService.OVERWRITE_ACTIVITY_TIME).asBoolean());
}
}
}
} catch (IOException e) {
@ -639,8 +643,8 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
transportService.process(deviceSessionCtx.getSessionInfo(), DefaultTransportService.getSessionEventMsg(SessionEvent.OPEN), new TransportServiceCallback<Void>() {
@Override
public void onSuccess(Void msg) {
transportService.registerAsyncSession(deviceSessionCtx.getSessionInfo(), MqttTransportHandler.this);
checkGatewaySession();
SessionMetaData sessionMetaData = transportService.registerAsyncSession(deviceSessionCtx.getSessionInfo(), MqttTransportHandler.this);
checkGatewaySession(sessionMetaData);
ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_ACCEPTED, connectMessage));
log.info("[{}] Client connected!", sessionId);
}

5
common/transport/transport-api/pom.xml

@ -114,9 +114,12 @@
<dependency>
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-core</artifactId>
<version>1.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-server-cf</artifactId>
</dependency>
</dependencies>
<build>

2
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;

8
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;
@ -94,11 +94,11 @@ public interface TransportService {
void process(SessionInfoProto sessionInfo, ClaimDeviceMsg msg, TransportServiceCallback<Void> callback);
void registerAsyncSession(SessionInfoProto sessionInfo, SessionMsgListener listener);
SessionMetaData registerAsyncSession(SessionInfoProto sessionInfo, SessionMsgListener listener);
void registerSyncSession(SessionInfoProto sessionInfo, SessionMsgListener listener, long timeout);
SessionMetaData registerSyncSession(SessionInfoProto sessionInfo, SessionMsgListener listener, long timeout);
void reportActivity(SessionInfoProto sessionInfo);
SessionMetaData reportActivity(SessionInfoProto sessionInfo);
void deregisterSession(SessionInfoProto sessionInfo);
}

3
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;
@ -430,6 +429,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());

5
common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/auth/SessionInfoCreator.java

@ -15,16 +15,17 @@
*/
package org.thingsboard.server.common.transport.auth;
import lombok.extern.slf4j.Slf4j;
import org.thingsboard.server.common.transport.TransportContext;
import org.thingsboard.server.gen.transport.TransportProtos;
import java.util.UUID;
@Slf4j
public class SessionInfoCreator {
public static TransportProtos.SessionInfoProto create(ValidateDeviceCredentialsResponse msg, TransportContext context, UUID sessionId) {
return TransportProtos.SessionInfoProto.newBuilder()
.setNodeId(context.getNodeId())
return TransportProtos.SessionInfoProto.newBuilder().setNodeId(context.getNodeId())
.setSessionIdMSB(sessionId.getMostSignificantBits())
.setSessionIdLSB(sessionId.getLeastSignificantBits())
.setDeviceIdMSB(msg.getDeviceInfo().getDeviceId().getId().getMostSignificantBits())

53
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<String /** clientEndPoint */, TransportProtos.ValidateDeviceCredentialsResponseMsg> sessions;

134
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<ObjectModel> 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;
}
}

27
common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/DefaultTransportService.java

@ -61,6 +61,7 @@ import org.thingsboard.server.common.transport.util.JsonUtils;
import org.thingsboard.server.gen.transport.TransportProtos;
import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceRequestMsg;
import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceResponseMsg;
import org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto;
import org.thingsboard.server.gen.transport.TransportProtos.ToCoreMsg;
import org.thingsboard.server.gen.transport.TransportProtos.ToRuleEngineMsg;
import org.thingsboard.server.gen.transport.TransportProtos.ToTransportMsg;
@ -107,6 +108,8 @@ import java.util.concurrent.atomic.AtomicInteger;
@TbTransportComponent
public class DefaultTransportService implements TransportService {
public static final String OVERWRITE_ACTIVITY_TIME = "overwriteActivityTime";
@Value("${transport.sessions.inactivity_timeout}")
private long sessionInactivityTimeout;
@Value("${transport.sessions.report_timeout}")
@ -233,8 +236,10 @@ public class DefaultTransportService implements TransportService {
}
@Override
public void registerAsyncSession(TransportProtos.SessionInfoProto sessionInfo, SessionMsgListener listener) {
sessions.putIfAbsent(toSessionId(sessionInfo), new SessionMetaData(sessionInfo, TransportProtos.SessionType.ASYNC, listener));
public SessionMetaData registerAsyncSession(TransportProtos.SessionInfoProto sessionInfo, SessionMsgListener listener) {
SessionMetaData newValue = new SessionMetaData(sessionInfo, TransportProtos.SessionType.ASYNC, listener);
SessionMetaData oldValue = sessions.putIfAbsent(toSessionId(sessionInfo), newValue);
return oldValue != null ? oldValue : newValue;
}
@Override
@ -509,8 +514,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) {
@ -530,7 +535,7 @@ public class DefaultTransportService implements TransportService {
if (sessionInfo.getGwSessionIdMSB() != 0 &&
sessionInfo.getGwSessionIdLSB() != 0) {
SessionMetaData gwMetaData = sessions.get(new UUID(sessionInfo.getGwSessionIdMSB(), sessionInfo.getGwSessionIdLSB()));
if (gwMetaData != null) {
if (gwMetaData != null && gwMetaData.isOverwriteActivityTime()) {
lastActivityTime = Math.max(gwMetaData.getLastActivityTime(), lastActivityTime);
}
}
@ -564,7 +569,7 @@ public class DefaultTransportService implements TransportService {
}
@Override
public void registerSyncSession(TransportProtos.SessionInfoProto sessionInfo, SessionMsgListener listener, long timeout) {
public SessionMetaData registerSyncSession(TransportProtos.SessionInfoProto sessionInfo, SessionMsgListener listener, long timeout) {
SessionMetaData currentSession = new SessionMetaData(sessionInfo, TransportProtos.SessionType.SYNC, listener);
sessions.putIfAbsent(toSessionId(sessionInfo), currentSession);
@ -574,6 +579,7 @@ public class DefaultTransportService implements TransportService {
}, timeout, TimeUnit.MILLISECONDS);
currentSession.setScheduledFuture(executorFuture);
return currentSession;
}
@Override
@ -728,8 +734,13 @@ public class DefaultTransportService implements TransportService {
.setDeviceProfileIdMSB(deviceProfileIdMSB)
.setDeviceProfileIdLSB(deviceProfileIdLSB)
.setDeviceName(device.getName())
.setDeviceType(device.getType())
.build();
.setDeviceType(device.getType()).build();
if (device.getAdditionalInfo().has("gateway")
&& device.getAdditionalInfo().get("gateway").asBoolean()
&& device.getAdditionalInfo().has(OVERWRITE_ACTIVITY_TIME)
&& device.getAdditionalInfo().get(OVERWRITE_ACTIVITY_TIME).isBoolean()) {
md.setOverwriteActivityTime(device.getAdditionalInfo().get(OVERWRITE_ACTIVITY_TIME).asBoolean());
}
md.setSessionInfo(newSessionInfo);
transportCallbackExecutor.submit(() -> md.getListener().onDeviceUpdate(newSessionInfo, device, Optional.ofNullable(newDeviceProfile)));
}

3
common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/SessionMetaData.java

@ -25,7 +25,7 @@ import java.util.concurrent.ScheduledFuture;
* Created by ashvayka on 15.10.18.
*/
@Data
class SessionMetaData {
public class SessionMetaData {
private volatile TransportProtos.SessionInfoProto sessionInfo;
private final TransportProtos.SessionType sessionType;
@ -36,6 +36,7 @@ class SessionMetaData {
private volatile long lastReportedActivityTime;
private volatile boolean subscribedToAttributes;
private volatile boolean subscribedToRPC;
private volatile boolean overwriteActivityTime;
SessionMetaData(TransportProtos.SessionInfoProto sessionInfo, TransportProtos.SessionType sessionType, SessionMsgListener listener) {
this.sessionInfo = sessionInfo;

4
dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java

@ -382,7 +382,9 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ
private Set<EntityId> getPropagationEntityIds(Alarm alarm) {
if (alarm.isPropagate()) {
List<EntityRelation> relations = relationService.findByTo(alarm.getTenantId(), alarm.getId(), RelationTypeGroup.ALARM);
return relations.stream().map(EntityRelation::getFrom).collect(Collectors.toSet());
Set<EntityId> propagationEntityIds = relations.stream().map(EntityRelation::getFrom).collect(Collectors.toSet());
propagationEntityIds.add(alarm.getOriginator());
return propagationEntityIds;
} else {
return Collections.singleton(alarm.getOriginator());
}

9
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) {

47
dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java

@ -180,10 +180,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) {
@ -201,8 +231,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")) {
@ -211,14 +240,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) {
@ -515,6 +536,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);
@ -588,7 +611,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);
}

1
dao/src/main/java/org/thingsboard/server/dao/user/UserServiceImpl.java

@ -186,6 +186,7 @@ public class UserServiceImpl extends AbstractEntityService implements UserServic
public UserCredentials requestPasswordReset(TenantId tenantId, String email) {
log.trace("Executing requestPasswordReset email [{}]", email);
validateString(email, "Incorrect email " + email);
DataValidator.validateEmail(email);
User user = userDao.findByEmail(tenantId, email);
if (user == null) {
throw new IncorrectParameterException(String.format("Unable to find user by email [%s]", email));

7
netty-mqtt/pom.xml

@ -67,11 +67,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -87,4 +82,4 @@
</plugin>
</plugins>
</build>
</project>
</project>

28
pom.xml

@ -62,9 +62,10 @@
<jackson-annotations.version>2.11.3</jackson-annotations.version>
<jackson-core.version>2.11.3</jackson-core.version>
<json-schema-validator.version>2.2.6</json-schema-validator.version>
<californium.version>2.2.3</californium.version>
<leshan-server.version>1.0.1</leshan-server.version>
<leshan-client.version>1.0.0</leshan-client.version>
<californium.version>2.6.0</californium.version>
<leshan-server.version>1.3.0</leshan-server.version>
<leshan-core.version>1.3.0</leshan-core.version>
<leshan-client.version>1.3.0</leshan-client.version>
<gson.version>2.6.2</gson.version>
<freemarker.version>2.3.30</freemarker.version>
<mail.version>1.6.2</mail.version>
@ -578,7 +579,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -1166,11 +1167,30 @@
<artifactId>leshan-server-redis</artifactId>
<version>${leshan-server.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-core</artifactId>
<version>${leshan-core.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>californium-core</artifactId>
<version>${californium.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>californium-core</artifactId>
<version>${californium.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>element-connector</artifactId>
<version>${californium.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>

19
rest-client/src/main/java/org/thingsboard/rest/client/RestClient.java

@ -127,6 +127,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;
@ -1106,6 +1107,24 @@ public class RestClient implements ClientHttpRequestInterceptor, Closeable {
return restTemplate.postForEntity(baseURL + "/api/device/credentials", deviceCredentials, DeviceCredentials.class).getBody();
}
public Optional<Device> saveDeviceWithCredentials(Device device, DeviceCredentials credentials) {
try {
Map<Class<?>, 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<Device> 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<Device> getTenantDevices(String type, PageLink pageLink) {
Map<String, String> params = new HashMap<>();
params.put("type", type);

26
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/AnonymousCredentials.java

@ -0,0 +1,26 @@
/**
* Copyright © 2016-2021 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.rule.engine.credentials;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class AnonymousCredentials implements ClientCredentials {
@Override
public CredentialsType getType() {
return CredentialsType.ANONYMOUS;
}
}

24
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/credentials/AnonymousCredentials.java → rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/BasicCredentials.java

@ -13,23 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.rule.engine.mqtt.credentials;
package org.thingsboard.rule.engine.credentials;
import io.netty.handler.ssl.SslContext;
import org.thingsboard.mqtt.MqttClientConfig;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.util.Optional;
public class AnonymousCredentials implements MqttClientCredentials {
@Override
public Optional<SslContext> initSslContext() {
return Optional.empty();
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class BasicCredentials implements ClientCredentials {
private String username;
private String password;
@Override
public void configure(MqttClientConfig config) {
public CredentialsType getType() {
return CredentialsType.BASIC;
}
}

35
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/credentials/CertPemClientCredentials.java → rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/CertPemCredentials.java

@ -13,10 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.rule.engine.mqtt.credentials;
package org.thingsboard.rule.engine.credentials;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import lombok.Data;
@ -29,7 +28,6 @@ import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.springframework.util.StringUtils;
import org.thingsboard.mqtt.MqttClientConfig;
import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
@ -51,13 +49,11 @@ import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Optional;
@Data
@Slf4j
@JsonIgnoreProperties(ignoreUnknown = true)
public class CertPemClientCredentials implements MqttClientCredentials {
public class CertPemCredentials implements ClientCredentials {
private static final String TLS_VERSION = "TLSv1.2";
private String caCert;
@ -66,25 +62,28 @@ public class CertPemClientCredentials implements MqttClientCredentials {
private String password;
@Override
public Optional<SslContext> initSslContext() {
public CredentialsType getType() {
return CredentialsType.CERT_PEM;
}
@Override
public SslContext initSslContext() {
try {
Security.addProvider(new BouncyCastleProvider());
return Optional.of(SslContextBuilder.forClient()
.keyManager(createAndInitKeyManagerFactory())
.trustManager(createAndInitTrustManagerFactory())
.clientAuth(ClientAuth.REQUIRE)
.build());
SslContextBuilder builder = SslContextBuilder.forClient();
if (StringUtils.hasLength(caCert)) {
builder.trustManager(createAndInitTrustManagerFactory());
}
if (StringUtils.hasLength(cert) && StringUtils.hasLength(privateKey)) {
builder.keyManager(createAndInitKeyManagerFactory());
}
return builder.build();
} catch (Exception e) {
log.error("[{}:{}] Creating TLS factory failed!", caCert, cert, e);
throw new RuntimeException("Creating TLS factory failed!", e);
}
}
@Override
public void configure(MqttClientConfig config) {
}
private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception {
X509Certificate certHolder = readCertFile(cert);
Object keyObject = readPrivateKeyFile(privateKey);
@ -122,7 +121,7 @@ public class CertPemClientCredentials implements MqttClientCredentials {
return keyManagerFactory;
}
private TrustManagerFactory createAndInitTrustManagerFactory() throws Exception {
protected TrustManagerFactory createAndInitTrustManagerFactory() throws Exception {
X509Certificate caCertHolder;
caCertHolder = readCertFile(caCert);

26
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/credentials/MqttClientCredentials.java → rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/ClientCredentials.java

@ -13,29 +13,29 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.rule.engine.mqtt.credentials;
package org.thingsboard.rule.engine.credentials;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.netty.handler.ssl.SslContext;
import org.thingsboard.mqtt.MqttClientConfig;
import io.netty.handler.ssl.SslContextBuilder;
import org.thingsboard.rule.engine.mqtt.azure.AzureIotHubSasCredentials;
import java.util.Optional;
import javax.net.ssl.SSLException;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = AnonymousCredentials.class, name = "anonymous"),
@JsonSubTypes.Type(value = BasicCredentials.class, name = "basic"),
@JsonSubTypes.Type(value = AzureIotHubSasCredentials.class, name = "sas"),
@JsonSubTypes.Type(value = CertPemClientCredentials.class, name = "cert.PEM")})
public interface MqttClientCredentials {
@JsonSubTypes.Type(value = CertPemCredentials.class, name = "cert.PEM")})
public interface ClientCredentials {
@JsonIgnore
CredentialsType getType();
Optional<SslContext> initSslContext();
void configure(MqttClientConfig config);
@JsonIgnore
default SslContext initSslContext() throws SSLException{
return SslContextBuilder.forClient().build();
}
}

17
ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-object-add-instances-list.component.scss → rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/CredentialsType.java

@ -13,10 +13,17 @@
* 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;
package org.thingsboard.rule.engine.credentials;
public enum CredentialsType {
ANONYMOUS("anonymous"),
BASIC("basic"),
SAS("sas"),
CERT_PEM("cert.PEM");
private final String label;
CredentialsType(String label) {
this.label = label;
}
}
}

42
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/TbMqttNode.java

@ -18,7 +18,6 @@ package org.thingsboard.rule.engine.mqtt;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
@ -31,13 +30,15 @@ import org.thingsboard.rule.engine.api.TbNode;
import org.thingsboard.rule.engine.api.TbNodeConfiguration;
import org.thingsboard.rule.engine.api.TbNodeException;
import org.thingsboard.rule.engine.api.util.TbNodeUtils;
import org.thingsboard.rule.engine.credentials.BasicCredentials;
import org.thingsboard.rule.engine.credentials.ClientCredentials;
import org.thingsboard.rule.engine.credentials.CredentialsType;
import org.thingsboard.server.common.data.plugin.ComponentType;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
import javax.net.ssl.SSLException;
import java.nio.charset.Charset;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@ -77,14 +78,14 @@ public class TbMqttNode implements TbNode {
String topic = TbNodeUtils.processPattern(this.mqttNodeConfiguration.getTopicPattern(), msg.getMetaData());
this.mqttClient.publish(topic, Unpooled.wrappedBuffer(msg.getData().getBytes(UTF8)), MqttQoS.AT_LEAST_ONCE)
.addListener(future -> {
if (future.isSuccess()) {
ctx.tellSuccess(msg);
} else {
TbMsg next = processException(ctx, msg, future.cause());
ctx.tellFailure(next, future.cause());
}
}
);
if (future.isSuccess()) {
ctx.tellSuccess(msg);
} else {
TbMsg next = processException(ctx, msg, future.cause());
ctx.tellFailure(next, future.cause());
}
}
);
}
private TbMsg processException(TbContext ctx, TbMsg origMsg, Throwable e) {
@ -101,13 +102,13 @@ public class TbMqttNode implements TbNode {
}
protected MqttClient initClient(TbContext ctx) throws Exception {
Optional<SslContext> sslContextOpt = initSslContext();
MqttClientConfig config = sslContextOpt.isPresent() ? new MqttClientConfig(sslContextOpt.get()) : new MqttClientConfig();
MqttClientConfig config = new MqttClientConfig(getSslContext());
if (!StringUtils.isEmpty(this.mqttNodeConfiguration.getClientId())) {
config.setClientId(this.mqttNodeConfiguration.getClientId());
}
config.setCleanSession(this.mqttNodeConfiguration.isCleanSession());
this.mqttNodeConfiguration.getCredentials().configure(config);
prepareMqttClientConfig(config);
MqttClient client = MqttClient.create(config, null);
client.setEventLoop(ctx.getSharedEventLoop());
Future<MqttConnectResult> connectFuture = client.connect(this.mqttNodeConfiguration.getHost(), this.mqttNodeConfiguration.getPort());
@ -129,12 +130,17 @@ public class TbMqttNode implements TbNode {
return client;
}
private Optional<SslContext> initSslContext() throws SSLException {
Optional<SslContext> result = this.mqttNodeConfiguration.getCredentials().initSslContext();
if (this.mqttNodeConfiguration.isSsl() && !result.isPresent()) {
result = Optional.of(SslContextBuilder.forClient().build());
protected void prepareMqttClientConfig(MqttClientConfig config) throws SSLException {
ClientCredentials credentials = this.mqttNodeConfiguration.getCredentials();
if (credentials.getType() == CredentialsType.BASIC) {
BasicCredentials basicCredentials = (BasicCredentials) credentials;
config.setUsername(basicCredentials.getUsername());
config.setPassword(basicCredentials.getPassword());
}
return result;
}
private SslContext getSslContext() throws SSLException {
return this.mqttNodeConfiguration.isSsl() ? this.mqttNodeConfiguration.getCredentials().initSslContext() : null;
}
}

6
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/TbMqttNodeConfiguration.java

@ -17,8 +17,8 @@ package org.thingsboard.rule.engine.mqtt;
import lombok.Data;
import org.thingsboard.rule.engine.api.NodeConfiguration;
import org.thingsboard.rule.engine.mqtt.credentials.AnonymousCredentials;
import org.thingsboard.rule.engine.mqtt.credentials.MqttClientCredentials;
import org.thingsboard.rule.engine.credentials.AnonymousCredentials;
import org.thingsboard.rule.engine.credentials.ClientCredentials;
@Data
public class TbMqttNodeConfiguration implements NodeConfiguration<TbMqttNodeConfiguration> {
@ -31,7 +31,7 @@ public class TbMqttNodeConfiguration implements NodeConfiguration<TbMqttNodeConf
private boolean cleanSession;
private boolean ssl;
private MqttClientCredentials credentials;
private ClientCredentials credentials;
@Override
public TbMqttNodeConfiguration defaultConfiguration() {

42
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/azure/AzureIotHubSasCredentials.java

@ -24,35 +24,35 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.thingsboard.common.util.AzureIotHubUtil;
import org.thingsboard.mqtt.MqttClientConfig;
import org.thingsboard.rule.engine.mqtt.credentials.MqttClientCredentials;
import org.thingsboard.rule.engine.credentials.CertPemCredentials;
import org.thingsboard.rule.engine.credentials.CredentialsType;
import javax.net.ssl.TrustManagerFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Optional;
@Data
@Slf4j
@JsonIgnoreProperties(ignoreUnknown = true)
public class AzureIotHubSasCredentials implements MqttClientCredentials {
public class AzureIotHubSasCredentials extends CertPemCredentials {
private String sasKey;
private String caCert;
@Override
public Optional<SslContext> initSslContext() {
public SslContext initSslContext() {
try {
Security.addProvider(new BouncyCastleProvider());
if (caCert == null || caCert.isEmpty()) {
caCert = AzureIotHubUtil.getDefaultCaCert();
}
return Optional.of(SslContextBuilder.forClient()
return SslContextBuilder.forClient()
.trustManager(createAndInitTrustManagerFactory())
.clientAuth(ClientAuth.REQUIRE)
.build());
.build();
} catch (Exception e) {
log.error("[{}] Creating TLS factory failed!", caCert, e);
throw new RuntimeException("Creating TLS factory failed!", e);
@ -60,32 +60,8 @@ public class AzureIotHubSasCredentials implements MqttClientCredentials {
}
@Override
public void configure(MqttClientConfig config) {
public CredentialsType getType() {
return CredentialsType.SAS;
}
private TrustManagerFactory createAndInitTrustManagerFactory() throws Exception {
X509Certificate caCertHolder;
caCertHolder = readCertFile(caCert);
KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
caKeyStore.load(null, null);
caKeyStore.setCertificateEntry("caCert-cert", caCertHolder);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(caKeyStore);
return trustManagerFactory;
}
private X509Certificate readCertFile(String fileContent) throws Exception {
X509Certificate certificate = null;
if (fileContent != null && !fileContent.trim().isEmpty()) {
fileContent = fileContent.replace("-----BEGIN CERTIFICATE-----", "")
.replace("-----END CERTIFICATE-----", "")
.replaceAll("\\s", "");
byte[] decoded = Base64.decodeBase64(fileContent);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(decoded));
}
return certificate;
}
}

55
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/azure/TbAzureIotHubNode.java

@ -18,6 +18,7 @@ package org.thingsboard.rule.engine.mqtt.azure;
import io.netty.handler.codec.mqtt.MqttVersion;
import io.netty.handler.ssl.SslContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.thingsboard.common.util.AzureIotHubUtil;
import org.thingsboard.mqtt.MqttClientConfig;
import org.thingsboard.rule.engine.api.RuleNode;
@ -25,13 +26,15 @@ import org.thingsboard.rule.engine.api.TbContext;
import org.thingsboard.rule.engine.api.TbNodeConfiguration;
import org.thingsboard.rule.engine.api.TbNodeException;
import org.thingsboard.rule.engine.api.util.TbNodeUtils;
import org.thingsboard.rule.engine.credentials.BasicCredentials;
import org.thingsboard.rule.engine.credentials.CertPemCredentials;
import org.thingsboard.rule.engine.credentials.ClientCredentials;
import org.thingsboard.rule.engine.credentials.CredentialsType;
import org.thingsboard.rule.engine.mqtt.TbMqttNode;
import org.thingsboard.rule.engine.mqtt.TbMqttNodeConfiguration;
import org.thingsboard.rule.engine.mqtt.credentials.CertPemClientCredentials;
import org.thingsboard.rule.engine.mqtt.credentials.MqttClientCredentials;
import org.thingsboard.server.common.data.plugin.ComponentType;
import java.util.Optional;
import javax.net.ssl.SSLException;
@Slf4j
@RuleNode(
@ -50,37 +53,25 @@ public class TbAzureIotHubNode extends TbMqttNode {
this.mqttNodeConfiguration = TbNodeUtils.convert(configuration, TbMqttNodeConfiguration.class);
mqttNodeConfiguration.setPort(8883);
mqttNodeConfiguration.setCleanSession(true);
MqttClientCredentials credentials = mqttNodeConfiguration.getCredentials();
mqttNodeConfiguration.setCredentials(new MqttClientCredentials() {
@Override
public Optional<SslContext> initSslContext() {
if (credentials instanceof AzureIotHubSasCredentials) {
AzureIotHubSasCredentials sasCredentials = (AzureIotHubSasCredentials) credentials;
if (sasCredentials.getCaCert() == null || sasCredentials.getCaCert().isEmpty()) {
sasCredentials.setCaCert(AzureIotHubUtil.getDefaultCaCert());
}
} else if (credentials instanceof CertPemClientCredentials) {
CertPemClientCredentials pemCredentials = (CertPemClientCredentials) credentials;
if (pemCredentials.getCaCert() == null || pemCredentials.getCaCert().isEmpty()) {
pemCredentials.setCaCert(AzureIotHubUtil.getDefaultCaCert());
}
}
return credentials.initSslContext();
ClientCredentials credentials = mqttNodeConfiguration.getCredentials();
if (CredentialsType.CERT_PEM == credentials.getType()) {
CertPemCredentials pemCredentials = (CertPemCredentials) credentials;
if (pemCredentials.getCaCert() == null || pemCredentials.getCaCert().isEmpty()) {
pemCredentials.setCaCert(AzureIotHubUtil.getDefaultCaCert());
}
@Override
public void configure(MqttClientConfig config) {
config.setProtocolVersion(MqttVersion.MQTT_3_1_1);
config.setUsername(AzureIotHubUtil.buildUsername(mqttNodeConfiguration.getHost(), config.getClientId()));
if (credentials instanceof AzureIotHubSasCredentials) {
AzureIotHubSasCredentials sasCredentials = (AzureIotHubSasCredentials) credentials;
config.setPassword(AzureIotHubUtil.buildSasToken(mqttNodeConfiguration.getHost(), sasCredentials.getSasKey()));
}
}
});
}
this.mqttClient = initClient(ctx);
} catch (Exception e) {
throw new TbNodeException(e);
} }
}
}
protected void prepareMqttClientConfig(MqttClientConfig config) throws SSLException {
config.setProtocolVersion(MqttVersion.MQTT_3_1_1);
config.setUsername(AzureIotHubUtil.buildUsername(mqttNodeConfiguration.getHost(), config.getClientId()));
ClientCredentials credentials = mqttNodeConfiguration.getCredentials();
if (CredentialsType.SAS == credentials.getType()) {
config.setPassword(AzureIotHubUtil.buildSasToken(mqttNodeConfiguration.getHost(), ((AzureIotHubSasCredentials) credentials).getSasKey()));
}
}
}

3
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/azure/TbAzureIotHubNodeConfiguration.java

@ -16,10 +16,7 @@
package org.thingsboard.rule.engine.mqtt.azure;
import lombok.Data;
import org.thingsboard.rule.engine.api.NodeConfiguration;
import org.thingsboard.rule.engine.mqtt.TbMqttNodeConfiguration;
import org.thingsboard.rule.engine.mqtt.credentials.AnonymousCredentials;
import org.thingsboard.rule.engine.mqtt.credentials.MqttClientCredentials;
@Data
public class TbAzureIotHubNodeConfiguration extends TbMqttNodeConfiguration {

42
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/credentials/BasicCredentials.java

@ -1,42 +0,0 @@
/**
* Copyright © 2016-2021 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.rule.engine.mqtt.credentials;
import io.netty.handler.ssl.SslContext;
import lombok.Data;
import org.thingsboard.mqtt.MqttClientConfig;
import java.util.Optional;
@Data
public class BasicCredentials implements MqttClientCredentials {
private String username;
private String password;
@Override
public Optional<SslContext> initSslContext() {
return Optional.empty();
}
@Override
public void configure(MqttClientConfig config) {
config.setUsername(username);
config.setPassword(password);
}
}

7
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/profile/AlarmState.java

@ -291,4 +291,11 @@ class AlarmState {
}
return updated;
}
public void processAckAlarm(Alarm alarm) {
if (currentAlarm != null && currentAlarm.getId().equals(alarm.getId())) {
currentAlarm.setStatus(alarm.getStatus());
currentAlarm.setAckTs(alarm.getAckTs());
}
}
}

12
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/profile/DeviceState.java

@ -140,6 +140,8 @@ class DeviceState {
stateChanged = processAttributesDeleteNotification(ctx, msg);
} else if (msg.getType().equals(DataConstants.ALARM_CLEAR)) {
stateChanged = processAlarmClearNotification(ctx, msg);
} else if (msg.getType().equals(DataConstants.ALARM_ACK)) {
processAlarmAckNotification(ctx, msg);
} else {
ctx.tellSuccess(msg);
}
@ -161,6 +163,16 @@ class DeviceState {
return stateChanged;
}
private void processAlarmAckNotification(TbContext ctx, TbMsg msg) {
Alarm alarmNf = JacksonUtil.fromString(msg.getData(), Alarm.class);
for (DeviceProfileAlarm alarm : deviceProfile.getAlarmSettings()) {
AlarmState alarmState = alarmStates.computeIfAbsent(alarm.getId(),
a -> new AlarmState(this.deviceProfile, deviceId, alarm, getOrInitPersistedAlarmState(alarm)));
alarmState.processAckAlarm(alarmNf);
}
ctx.tellSuccess(msg);
}
private boolean processAttributesUpdateNotification(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException {
Set<AttributeKvEntry> attributes = JsonConverter.convertToAttributes(new JsonParser().parse(msg.getData()));
String scope = msg.getMetaData().getValue("scope");

21
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbHttpClient.java

@ -17,9 +17,9 @@ package org.thingsboard.rule.engine.rest;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.ssl.SslContextBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
@ -35,6 +35,7 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsAsyncClientHttpRequestFactory;
import org.springframework.http.client.Netty4ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.StringUtils;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
@ -44,6 +45,9 @@ import org.thingsboard.rule.engine.api.TbContext;
import org.thingsboard.rule.engine.api.TbNodeException;
import org.thingsboard.rule.engine.api.TbRelationTypes;
import org.thingsboard.rule.engine.api.util.TbNodeUtils;
import org.thingsboard.rule.engine.credentials.BasicCredentials;
import org.thingsboard.rule.engine.credentials.ClientCredentials;
import org.thingsboard.rule.engine.credentials.CredentialsType;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
@ -51,8 +55,10 @@ import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Deque;
import java.util.Optional;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.TimeUnit;
@ -129,11 +135,14 @@ public class TbHttpClient {
requestFactory.setReadTimeout(config.getReadTimeoutMs());
httpClient = new AsyncRestTemplate(requestFactory);
} else if (config.isUseSimpleClientHttpFactory()) {
if (CredentialsType.CERT_PEM == config.getCredentials().getType()) {
throw new TbNodeException("Simple HTTP Factory does not support CERT PEM credentials!");
}
httpClient = new AsyncRestTemplate();
} else {
this.eventLoopGroup = new NioEventLoopGroup();
Netty4ClientHttpRequestFactory nettyFactory = new Netty4ClientHttpRequestFactory(this.eventLoopGroup);
nettyFactory.setSslContext(SslContextBuilder.forClient().build());
nettyFactory.setSslContext(config.getCredentials().initSslContext());
nettyFactory.setReadTimeout(config.getReadTimeoutMs());
httpClient = new AsyncRestTemplate(nettyFactory);
}
@ -226,6 +235,13 @@ public class TbHttpClient {
private HttpHeaders prepareHeaders(TbMsgMetaData metaData) {
HttpHeaders headers = new HttpHeaders();
config.getHeaders().forEach((k, v) -> headers.add(TbNodeUtils.processPattern(k, metaData), TbNodeUtils.processPattern(v, metaData)));
ClientCredentials credentials = config.getCredentials();
if (CredentialsType.BASIC == credentials.getType()) {
BasicCredentials basicCredentials = (BasicCredentials) credentials;
String authString = basicCredentials.getUsername() + ":" + basicCredentials.getPassword();
String encodedAuthString = new String(Base64.encodeBase64(authString.getBytes(StandardCharsets.UTF_8)));
headers.add("Authorization", "Basic " + encodedAuthString);
}
return headers;
}
@ -259,4 +275,5 @@ public class TbHttpClient {
throw new TbNodeException("Proxy port out of range:" + proxyPort);
}
}
}

4
rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbRestApiCallNodeConfiguration.java

@ -18,6 +18,8 @@ package org.thingsboard.rule.engine.rest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.thingsboard.rule.engine.api.NodeConfiguration;
import org.thingsboard.rule.engine.credentials.AnonymousCredentials;
import org.thingsboard.rule.engine.credentials.ClientCredentials;
import java.util.Collections;
import java.util.Map;
@ -42,6 +44,7 @@ public class TbRestApiCallNodeConfiguration implements NodeConfiguration<TbRestA
private String proxyUser;
private String proxyPassword;
private String proxyScheme;
private ClientCredentials credentials;
@Override
public TbRestApiCallNodeConfiguration defaultConfiguration() {
@ -55,6 +58,7 @@ public class TbRestApiCallNodeConfiguration implements NodeConfiguration<TbRestA
configuration.setUseRedisQueueForMsgPersistence(false);
configuration.setTrimQueue(false);
configuration.setEnableProxy(false);
configuration.setCredentials(new AnonymousCredentials());
return configuration;
}
}

2
rule-engine/rule-engine-components/src/main/resources/public/static/rulenode/rulenode-core-config.js

File diff suppressed because one or more lines are too long

60
transport/lwm2m/pom.xml

@ -45,11 +45,38 @@
</properties>
<dependencies>
<dependency>
<groupId>org.thingsboard.common.transport</groupId>
<artifactId>transport-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-server-cf</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-client-cf</artifactId>
@ -59,7 +86,6 @@
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-server-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@ -78,37 +104,23 @@
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>californium-core</artifactId>
<version>${californium.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>californium-core</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.eclipse.californium</groupId>-->
<!-- <artifactId>scandium</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>element-connector</artifactId>
<version>${californium.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.thingsboard.common.transport</groupId>
<artifactId>lwm2m</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.common</groupId>
<artifactId>queue</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.sun.winsw</groupId>
<artifactId>winsw</artifactId>
<classifier>bin</classifier>
<type>exe</type>
<scope>provided</scope>
</dependency>
</dependencies>
<build>

BIN
transport/lwm2m/src/main/data/credentials/serverKeyStore.jks

Binary file not shown.

403
transport/lwm2m/src/main/data/credentials/shell/lwM2M_credentials.sh

@ -0,0 +1,403 @@
#!/bin/bash
#
# Copyright © 2016-2021 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

57
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`

167
transport/lwm2m/src/main/data/models/LWM2M_Connectivity_Monitoring-v1_0_2.xml

@ -1,167 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright © 2016-2021 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.
-->
<LWM2M xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://openmobilealliance.org/tech/profiles/LWM2M.xsd">
<Object ObjectType="MODefinition">
<Name>Connectivity Monitoring</Name>
<Description1>
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.
</Description1>
<ObjectID>4</ObjectID>
<ObjectURN>urn:oma:lwm2m:oma:4</ObjectURN>
<LWM2MVersion>1.0</LWM2MVersion>
<ObjectVersion>1.0</ObjectVersion>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Resources>
<Item ID="0">
<Name>Network Bearer</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Mandatory</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>0-50</RangeEnumeration>
<Units/>
<Description>
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.
</Description>
</Item>
<Item ID="1">
<Name>Available Network Bearer</Name>
<Operations>R</Operations>
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Mandatory</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>0-50</RangeEnumeration>
<Units/>
<Description>
Indicates a list of current available network bearer. Each Resource Instance has a value from the network bearer list.
</Description>
</Item>
<Item ID="2">
<Name>Radio Signal Strength</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Mandatory</Mandatory>
<Type>Integer</Type>
<RangeEnumeration/>
<Units>dBm</Units>
<Description>
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).
</Description>
</Item>
<Item ID="3">
<Name>Link Quality</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration/>
<Units/>
<Description>
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]).
</Description>
</Item>
<Item ID="4">
<Name>IP Addresses</Name>
<Operations>R</Operations>
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Mandatory</Mandatory>
<Type>String</Type>
<RangeEnumeration/>
<Units/>
<Description>
The IP addresses assigned to the connectivity interface. (e.g. IPv4, IPv6, etc.)
</Description>
</Item>
<Item ID="5">
<Name>Router IP Addresses</Name>
<Operations>R</Operations>
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>String</Type>
<RangeEnumeration/>
<Units/>
<Description>
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.
</Description>
</Item>
<Item ID="6">
<Name>Link Utilization</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>0-100</RangeEnumeration>
<Units>%</Units>
<Description>
The percentage indicating the average utilization of the link to the next-hop IP router.
</Description>
</Item>
<Item ID="7">
<Name>APN</Name>
<Operations>R</Operations>
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>String</Type>
<RangeEnumeration/>
<Units/>
<Description>
Access Point Name in case Network Bearer Resource is a Cellular Network.
</Description>
</Item>
<Item ID="8">
<Name>Cell ID</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration/>
<Units/>
<Description>
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].
</Description>
</Item>
<Item ID="9">
<Name>SMNC</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>0-999</RangeEnumeration>
<Units>%</Units>
<Description>
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].
</Description>
</Item>
<Item ID="10">
<Name>SMCC</Name>
<Operations>R</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>0-999</RangeEnumeration>
<Units/>
<Description>
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].
</Description>
</Item>
</Resources>
<Description2/>
</Object>
</LWM2M>

164
transport/lwm2m/src/main/data/models/LwM2M_BinaryAppDataContainer-v1_0_1.xml

@ -1,164 +0,0 @@
<!--
Copyright © 2016-2021 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.
-->
<?xml version="1.0" encoding="UTF-8"?>
<!--
FILE INFORMATION
OMA Permanent Document
File: OMA-SUP-LwM2M_BinaryAppDataContainer-V1_0_1-20190221-A
Type: xml
Public Reachable Information
Path: http://www.openmobilealliance.org/tech/profiles
Name: LwM2M_BinaryAppDataContainer-v1_0_1.xml
NORMATIVE INFORMATION
Information about this file can be found in the latest revision of
OMA-TS-LWM2M_BinaryAppDataContainer-V1_0_1
This is available at http://www.openmobilealliance.org/
Send comments to https://github.com/OpenMobileAlliance/OMA_LwM2M_for_Developers/issues
CHANGE HISTORY
15062018 Status changed to Approved by DM, Doc Ref # OMA-DM&SE-2018-0061-INP_LWM2M_APPDATA_V1_0_ERP_for_final_Approval
21022019 Status changed to Approved by IPSO, Doc Ref # OMA-IPSO-2019-0025-INP_LwM2M_Object_App_Data_Container_1_0_1_for_Final_Approval
LEGAL DISCLAIMER
Copyright 2019 Open Mobile Alliance.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
The above license is used as a license under copyright only. Please
reference the OMA IPR Policy for patent licensing terms:
https://www.omaspecworks.org/about/intellectual-property-rights/
-->
<LWM2M xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://openmobilealliance.org/tech/profiles/LWM2M.xsd">
<Object ObjectType="MODefinition">
<Name>BinaryAppDataContainer</Name>
<Description1><![CDATA[This LwM2M Objects provides the application service data related to a LwM2M Server, eg. Water meter data.
There are several methods to create instance to indicate the message direction based on the negotiation between Application and LwM2M. The Client and Server should negotiate the instance(s) used to exchange the data. For example:
- Using a single instance for both directions communication, from Client to Server and from Server to Client.
- Using an instance for communication from Client to Server and another one for communication from Server to Client
- Using several instances
]]></Description1>
<ObjectID>19</ObjectID>
<ObjectURN>urn:oma:lwm2m:oma:19</ObjectURN>
<LWM2MVersion>1.0</LWM2MVersion>
<ObjectVersion>1.0</ObjectVersion>
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Resources>
<Item ID="0"><Name>Data</Name>
<Operations>RW</Operations>
<!-- <MultipleInstances>Single</MultipleInstances>-->
<!-- <Mandatory>Optional</Mandatory>-->
<!-- <Type>String</Type>-->
<MultipleInstances>Multiple</MultipleInstances>
<Mandatory>Mandatory</Mandatory>
<Type>Opaque</Type>
<RangeEnumeration />
<Units />
<Description><![CDATA[Indicates the application data content.]]></Description>
</Item>
<Item ID="1"><Name>Data Priority</Name>
<Operations>RW</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>1 bytes</RangeEnumeration>
<Units />
<Description><![CDATA[Indicates the Application data priority:
0:Immediate
1:BestEffort
2:Latest
3-100: Reserved for future use.
101-254: Proprietary mode.]]></Description>
</Item>
<Item ID="2"><Name>Data Creation Time</Name>
<Operations>RW</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Time</Type>
<RangeEnumeration />
<Units />
<Description><![CDATA[Indicates the Data instance creation timestamp.]]></Description>
</Item>
<Item ID="3"><Name>Data Description</Name>
<Operations>RW</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>String</Type>
<RangeEnumeration>32 bytes</RangeEnumeration>
<Units />
<Description><![CDATA[Indicates the data description.
e.g. "meter reading".]]></Description>
</Item>
<Item ID="4"><Name>Data Format</Name>
<Operations>RW</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>String</Type>
<RangeEnumeration>32 bytes</RangeEnumeration>
<Units />
<Description><![CDATA[Indicates the format of the Application Data.
e.g. YG-Meter-Water-Reading
UTF8-string
]]></Description>
</Item>
<Item ID="5"><Name>App ID</Name>
<Operations>RW</Operations>
<MultipleInstances>Single</MultipleInstances>
<Mandatory>Optional</Mandatory>
<Type>Integer</Type>
<RangeEnumeration>2 bytes</RangeEnumeration>
<Units />
<Description><![CDATA[Indicates the destination Application ID.]]></Description>
</Item></Resources>
<Description2><![CDATA[]]></Description2>
</Object>
</LWM2M>

51
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}"

5
ui-ngx/angular.json

@ -228,6 +228,7 @@
},
"defaultProject": "thingsboard",
"cli": {
"packageManager": "yarn"
"packageManager": "yarn",
"analytics": false
}
}
}

2
ui-ngx/src/app/core/api/widget-api.models.ts

@ -53,6 +53,7 @@ import { EntityDataService } from '@core/api/entity-data.service';
import { PageData } from '@shared/models/page/page-data';
import { TranslateService } from '@ngx-translate/core';
import { AlarmDataService } from '@core/api/alarm-data.service';
import { IDashboardController } from '@home/components/dashboard-page/dashboard-page.models';
export interface TimewindowFunctions {
onUpdateTimewindow: (startTimeMs: number, endTimeMs: number, interval?: number) => void;
@ -137,6 +138,7 @@ export interface StateParams {
export type StateControllerHolder = () => IStateController;
export interface IStateController {
dashboardCtrl: IDashboardController;
getStateParams(): StateParams;
getStateParamsByStateId(stateId: string): StateParams;
openState(id: string, params?: StateParams, openRightLayout?: boolean): void;

35
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<PageData<DeviceProfile>> {
return this.http.get<PageData<DeviceProfile>>(`/api/deviceProfiles${pageLink.toQuery()}`, defaultHttpOptionsFromConfig(config));
@ -43,16 +43,31 @@ export class DeviceProfileService {
return this.http.get<DeviceProfile>(`/api/deviceProfile/${deviceProfileId}`, defaultHttpOptionsFromConfig(config));
}
public getLwm2mObjects(objectIds: number [], config?: RequestConfig): Observable<ObjectLwM2M[]> {
return this.http.get<ObjectLwM2M[]>(`/api/lwm2m/deviceProfile/${objectIds}`, defaultHttpOptionsFromConfig(config));
public getLwm2mObjects(sortOrder: SortOrder, objectIds?: number[], searchText?: string, config?: RequestConfig):
Observable<Array<ObjectLwM2M>> {
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<Array<ObjectLwM2M>>(url, defaultHttpOptionsFromConfig(config));
}
public getLwm2mBootstrapSecurityInfo(securityMode: string, bootstrapServerIs: boolean, config?: RequestConfig): Observable<ServerSecurityConfig> {
return this.http.get<ServerSecurityConfig>(`/api/lwm2m/deviceProfile/bootstrap/${securityMode}/${bootstrapServerIs}`, defaultHttpOptionsFromConfig(config));
public getLwm2mBootstrapSecurityInfo(securityMode: string, bootstrapServerIs: boolean,
config?: RequestConfig): Observable<ServerSecurityConfig> {
return this.http.get<ServerSecurityConfig>(
`/api/lwm2m/deviceProfile/bootstrap/${securityMode}/${bootstrapServerIs}`,
defaultHttpOptionsFromConfig(config)
);
}
public getLwm2mObjectsPage(pageLink: PageLink, config?: RequestConfig): Observable<PageData<ObjectLwM2M>> {
return this.http.get<PageData<ObjectLwM2M>>(`/api/lwm2m/deviceProfile/objects${pageLink.toQuery()}`, defaultHttpOptionsFromConfig(config));
return this.http.get<PageData<ObjectLwM2M>>(
`/api/lwm2m/deviceProfile/objects${pageLink.toQuery()}`,
defaultHttpOptionsFromConfig(config)
);
}
public saveDeviceProfile(deviceProfile: DeviceProfile, config?: RequestConfig): Observable<DeviceProfile> {

2
ui-ngx/src/app/modules/dashboard/dashboard-pages.module.ts

@ -19,7 +19,6 @@ import { CommonModule } from '@angular/common';
import { SharedModule } from '@shared/shared.module';
import { HomeComponentsModule } from '@modules/home/components/home-components.module';
import { HomeDialogsModule } from '@app/modules/home/dialogs/home-dialogs.module';
import { DashboardModule } from '@home/pages/dashboard/dashboard.module';
import { DashboardPagesRoutingModule } from './dashboard-pages.routing.module';
@NgModule({
@ -28,7 +27,6 @@ import { DashboardPagesRoutingModule } from './dashboard-pages.routing.module';
SharedModule,
HomeComponentsModule,
HomeDialogsModule,
DashboardModule,
DashboardPagesRoutingModule
]
})

3
ui-ngx/src/app/modules/dashboard/dashboard-pages.routing.module.ts

@ -18,7 +18,7 @@ import { Injectable, NgModule } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterModule, Routes } from '@angular/router';
import { Authority } from '@shared/models/authority.enum';
import { DashboardPageComponent } from '@home/pages/dashboard/dashboard-page.component';
import { DashboardPageComponent } from '@home/components/dashboard-page/dashboard-page.component';
import { Dashboard } from '@app/shared/models/dashboard.models';
import { DashboardService } from '@core/http/dashboard.service';
import { DashboardUtilsService } from '@core/services/dashboard-utils.service';
@ -95,6 +95,7 @@ const routes: Routes = [
exports: [RouterModule],
providers: [
WidgetEditorDashboardResolver,
DashboardResolver,
{
provide: MODULES_MAP,
useValue: modulesMap

0
ui-ngx/src/app/modules/home/pages/dashboard/add-widget-dialog.component.html → ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.html

0
ui-ngx/src/app/modules/home/pages/dashboard/add-widget-dialog.component.ts → ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.ts

8
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-page.component.html → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html

@ -21,7 +21,7 @@
<section class="tb-dashboard-toolbar"
[ngClass]="{ 'tb-dashboard-toolbar-opened': toolbarOpened,
'tb-dashboard-toolbar-closed': !toolbarOpened }">
<tb-dashboard-toolbar [fxShow]="!widgetEditMode" [forceFullscreen]="forceFullscreen"
<tb-dashboard-toolbar [fxShow]="!widgetEditMode && !hideToolbar" [forceFullscreen]="forceFullscreen"
[toolbarOpened]="toolbarOpened" (triggerClick)="openToolbar()">
<div class="tb-dashboard-action-panels" fxLayout="column" fxLayout.gt-sm="row"
fxLayoutAlign="center stretch" fxLayoutAlign.gt-sm="space-between center">
@ -52,6 +52,7 @@
[dashboardId]="dashboard.id ? dashboard.id.id : ''"
[isMobile]="isMobile"
[state]="dashboardCtx.state"
[currentState]="currentState"
[states]="dashboardConfiguration.states">
</tb-states-component>
</div>
@ -183,11 +184,12 @@
</mat-drawer-content>
</mat-drawer-container>
<section fxLayout="row" class="layout-wrap tb-footer-buttons" fxLayoutAlign="start end">
<tb-footer-fab-buttons [fxShow]="!isAddingWidget && isEdit && !widgetEditMode"
<tb-footer-fab-buttons *ngIf="!embedded"
[fxShow]="!isAddingWidget && isEdit && !widgetEditMode"
relative
[footerFabButtons]="addWidgetFabButtons">
</tb-footer-fab-buttons>
<button *ngIf="(isTenantAdmin() || isSystemAdmin()) && !forceFullscreen"
<button *ngIf="(isTenantAdmin() || isSystemAdmin()) && !forceFullscreen && !embedded"
mat-fab color="accent" class="tb-btn-footer"
[ngClass]="{'tb-hide': !isEdit || isAddingWidget}"
[disabled]="isLoading$ | async"

0
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-page.component.scss → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.scss

19
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-page.component.ts → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts

@ -78,23 +78,23 @@ import {
EntityAliasesDialogData
} from '@home/components/alias/entity-aliases-dialog.component';
import { EntityAliases } from '@app/shared/models/alias.models';
import { EditWidgetComponent } from '@home/pages/dashboard/edit-widget.component';
import { EditWidgetComponent } from '@home/components/dashboard-page/edit-widget.component';
import { WidgetsBundle } from '@shared/models/widgets-bundle.model';
import { AddWidgetDialogComponent, AddWidgetDialogData } from '@home/pages/dashboard/add-widget-dialog.component';
import { AddWidgetDialogComponent, AddWidgetDialogData } from '@home/components/dashboard-page/add-widget-dialog.component';
import { TranslateService } from '@ngx-translate/core';
import {
ManageDashboardLayoutsDialogComponent,
ManageDashboardLayoutsDialogData
} from '@home/pages/dashboard/layout/manage-dashboard-layouts-dialog.component';
} from '@home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component';
import { SelectTargetLayoutDialogComponent } from '@home/components/dashboard/select-target-layout-dialog.component';
import {
DashboardSettingsDialogComponent,
DashboardSettingsDialogData
} from '@home/pages/dashboard/dashboard-settings-dialog.component';
} from '@home/components/dashboard-page/dashboard-settings-dialog.component';
import {
ManageDashboardStatesDialogComponent,
ManageDashboardStatesDialogData
} from '@home/pages/dashboard/states/manage-dashboard-states-dialog.component';
} from '@home/components/dashboard-page/states/manage-dashboard-states-dialog.component';
import { ImportExportService } from '@home/components/import-export/import-export.service';
import { AuthState } from '@app/core/auth/auth.models';
import { FiltersDialogComponent, FiltersDialogData } from '@home/components/filter/filters-dialog.component';
@ -118,6 +118,12 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
@Input()
embedded = false;
@Input()
currentState: string;
@Input()
hideToolbar: boolean;
@Input()
dashboard: Dashboard;
dashboardConfiguration: DashboardConfiguration;
@ -162,6 +168,7 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
dashboardCtx: DashboardContext = {
instanceId: this.utils.guid(),
getDashboard: () => this.dashboard,
dashboardTimewindow: null,
state: null,
@ -221,7 +228,7 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
private rxSubscriptions = new Array<Subscription>();
get toolbarOpened(): boolean {
return !this.widgetEditMode &&
return !this.widgetEditMode && !this.hideToolbar &&
(this.toolbarAlwaysOpen() || this.isToolbarOpened || this.isEdit || this.showRightLayoutSwitch());
}
set toolbarOpened(toolbarOpened: boolean) {

1
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-page.models.ts → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.models.ts

@ -24,6 +24,7 @@ import { DashboardContextMenuItem, WidgetContextMenuItem } from '@home/models/da
export declare type DashboardPageScope = 'tenant' | 'customer';
export interface DashboardContext {
instanceId: string;
state: string;
getDashboard: () => Dashboard;
dashboardTimewindow: Timewindow;

0
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-settings-dialog.component.html → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-settings-dialog.component.html

0
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-settings-dialog.component.scss → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-settings-dialog.component.scss

0
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-settings-dialog.component.ts → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-settings-dialog.component.ts

0
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-toolbar.component.html → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-toolbar.component.html

0
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-toolbar.component.scss → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-toolbar.component.scss

0
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-toolbar.component.ts → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-toolbar.component.ts

0
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-widget-select.component.html → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html

0
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-widget-select.component.scss → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.scss

0
ui-ngx/src/app/modules/home/pages/dashboard/dashboard-widget-select.component.ts → ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save