Lwm2m: back: refactoring-light start

This commit is contained in:
nickAS21 2021-01-31 13:38:20 +02:00 committed by Andrew Shvayka
parent 9b4309c61a
commit f6eb3b1342
5 changed files with 64 additions and 68 deletions

View File

@ -581,6 +581,7 @@ transport:
request_pool_size: "${LWM2M_REQUEST_POOL_SIZE:100}" request_pool_size: "${LWM2M_REQUEST_POOL_SIZE:100}"
request_error_pool_size: "${LWM2M_REQUEST_ERROR_POOL_SIZE:10}" request_error_pool_size: "${LWM2M_REQUEST_ERROR_POOL_SIZE:10}"
registered_pool_size: "${LWM2M_REGISTERED_POOL_SIZE:10}" registered_pool_size: "${LWM2M_REGISTERED_POOL_SIZE:10}"
client_update_value_after_connect: "${CLIENT_UPDATE_VALUE_AFTER_CONNECT:false}"
update_registered_pool_size: "${LWM2M_UPDATE_REGISTERED_POOL_SIZE:10}" update_registered_pool_size: "${LWM2M_UPDATE_REGISTERED_POOL_SIZE:10}"
un_registered_pool_size: "${LWM2M_UN_REGISTERED_POOL_SIZE:10}" un_registered_pool_size: "${LWM2M_UN_REGISTERED_POOL_SIZE:10}"
secure: secure:

View File

@ -20,7 +20,6 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.eclipse.leshan.core.Link;
import org.eclipse.leshan.core.model.ResourceModel; import org.eclipse.leshan.core.model.ResourceModel;
import org.eclipse.leshan.core.node.LwM2mMultipleResource; import org.eclipse.leshan.core.node.LwM2mMultipleResource;
import org.eclipse.leshan.core.node.LwM2mObject; import org.eclipse.leshan.core.node.LwM2mObject;
@ -155,6 +154,7 @@ public class LwM2MTransportServiceImpl implements LwM2MTransportService {
lwM2MClient.setSessionUuid(UUID.randomUUID()); lwM2MClient.setSessionUuid(UUID.randomUUID());
this.sentLogsToThingsboard(LOG_LW2M_INFO + ": Client Registered", registration); this.sentLogsToThingsboard(LOG_LW2M_INFO + ": Client Registered", registration);
this.setLwM2mFromClientValue(lwServer, registration, lwM2MClient); this.setLwM2mFromClientValue(lwServer, registration, lwM2MClient);
lwM2MClient.setClientUpdateValueAfterConnect(this.context.getCtxServer().isClientUpdateValueAfterConnect());
SessionInfoProto sessionInfo = this.getValidateSessionInfo(registration); SessionInfoProto sessionInfo = this.getValidateSessionInfo(registration);
if (sessionInfo != null) { if (sessionInfo != null) {
lwM2MClient.setDeviceUuid(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB())); lwM2MClient.setDeviceUuid(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB()));
@ -165,7 +165,9 @@ public class LwM2MTransportServiceImpl implements LwM2MTransportService {
transportService.process(sessionInfo, DefaultTransportService.getSessionEventMsg(SessionEvent.OPEN), null); transportService.process(sessionInfo, DefaultTransportService.getSessionEventMsg(SessionEvent.OPEN), null);
transportService.process(sessionInfo, TransportProtos.SubscribeToAttributeUpdatesMsg.newBuilder().build(), null); transportService.process(sessionInfo, TransportProtos.SubscribeToAttributeUpdatesMsg.newBuilder().build(), null);
this.sentLogsToThingsboard(LOG_LW2M_INFO + ": Client create after Registration", registration); this.sentLogsToThingsboard(LOG_LW2M_INFO + ": Client create after Registration", registration);
if (this.context.getCtxServer().isClientUpdateValueAfterConnect()) {
this.putDelayedUpdateResourcesThingsboard(lwM2MClient); this.putDelayedUpdateResourcesThingsboard(lwM2MClient);
}
} else { } else {
log.error("Client: [{}] onRegistered [{}] name [{}] sessionInfo ", registration.getId(), registration.getEndpoint(), null); log.error("Client: [{}] onRegistered [{}] name [{}] sessionInfo ", registration.getId(), registration.getEndpoint(), null);
} }
@ -272,8 +274,11 @@ public class LwM2MTransportServiceImpl implements LwM2MTransportService {
/** /**
* #0 Add new ObjectModel to context * #0 Add new ObjectModel to context
* Create new LwM2MClient for current session -> setModelClient... * Create new LwM2MClient for current session -> setModelClient...
* #1 Add all ObjectLinks (instance) to control the process of executing requests to the client * if need all value after registration:
* #1.1 Add all ObjectLinks (instance) to control the process of executing requests to the client
* to get the client model with current values * to get the client model with current values
* if not need all value after registration (only observe)
* #1.2 Get observe
* #2 Get the client model with current values. Analyze the response in -> lwM2MTransportRequest.sendResponse * #2 Get the client model with current values. Analyze the response in -> lwM2MTransportRequest.sendResponse
* *
* @param lwServer - LeshanServer * @param lwServer - LeshanServer
@ -281,48 +286,35 @@ public class LwM2MTransportServiceImpl implements LwM2MTransportService {
* @param lwM2MClient - object with All parameters off client * @param lwM2MClient - object with All parameters off client
*/ */
private void setLwM2mFromClientValue(LeshanServer lwServer, Registration registration, LwM2MClient lwM2MClient) { private void setLwM2mFromClientValue(LeshanServer lwServer, Registration registration, LwM2MClient lwM2MClient) {
// #1.1
// get all instances in client
Set<String> clientInstances = ConcurrentHashMap.newKeySet();
Arrays.stream(registration.getObjectLinks()).forEach(url -> { Arrays.stream(registration.getObjectLinks()).forEach(url -> {
LwM2mPath pathIds = new LwM2mPath(url.getUrl()); LwM2mPath pathIds = new LwM2mPath(url.getUrl());
if (pathIds.isObjectInstance() && !pathIds.isResource()) { if (pathIds.isObjectInstance() && !pathIds.isResource()) {
// #1 clientInstances.add(url.getUrl());
lwM2MClient.getPendingRequests().add(url.getUrl());
// #2
lwM2MTransportRequest.sendAllRequest(lwServer, registration, url.getUrl(), GET_TYPE_OPER_READ, ContentFormat.TLV.getName(),
lwM2MClient, null, null, this.context.getCtxServer().getTimeout(), false);
} }
}); });
if (this.context.getCtxServer().isClientUpdateValueAfterConnect()) {
// #1 lwM2MClient.getPendingRequests().addAll(clientInstances);
for (Link url : registration.getObjectLinks()) { } else {
LwM2mPath pathIds = new LwM2mPath(url.getUrl()); // #1.2
if (pathIds.isObjectInstance() && !pathIds.isResource()) { UUID profileUUid = lwM2mInMemorySecurityStore.getSessions().get(registration.getId()).getProfileUuid();
lwM2MClient.getPendingRequests().add(url.getUrl()); JsonArray observeValue = lwM2mInMemorySecurityStore.getProfiles().get(profileUUid).getPostObserveProfile();
observeValue.forEach(path -> {
String[] resPath = path.getAsString().split("/");
String instance = "/" + resPath[1] + "/" + resPath[2];
if (clientInstances.contains(instance)) {
lwM2MClient.getPendingRequests().add(path.getAsString());
} }
} }
// #2 );
for (Link url : registration.getObjectLinks()) {
LwM2mPath pathIds = new LwM2mPath(url.getUrl());
if (pathIds.isObjectInstance() && !pathIds.isResource()) {
lwM2MTransportRequest.sendAllRequest(lwServer, registration, url.getUrl(), GET_TYPE_OPER_READ, ContentFormat.TLV.getName(),
lwM2MClient, null, null, this.context.getCtxServer().getTimeout(), false);
} }
}
// #1
Arrays.stream(registration.getObjectLinks()).forEach(url -> {
LwM2mPath pathIds = new LwM2mPath(url.getUrl());
if (pathIds.isObjectInstance() && !pathIds.isResource()) {
lwM2MClient.getPendingRequests().add(url.getUrl());
}
});
// #2 // #2
Arrays.stream(registration.getObjectLinks()).forEach(url -> { lwM2MClient.getPendingRequests().forEach(path -> {
LwM2mPath pathIds = new LwM2mPath(url.getUrl()); lwM2MTransportRequest.sendAllRequest(lwServer, registration, path, GET_TYPE_OPER_READ, ContentFormat.TLV.getName(),
if (pathIds.isObjectInstance() && !pathIds.isResource()) {
lwM2MTransportRequest.sendAllRequest(lwServer, registration, url.getUrl(), GET_TYPE_OPER_READ, ContentFormat.TLV.getName(),
lwM2MClient, null, null, this.context.getCtxServer().getTimeout(), false); lwM2MClient, null, null, this.context.getCtxServer().getTimeout(), false);
}
}); });
} }
@ -711,21 +703,14 @@ public class LwM2MTransportServiceImpl implements LwM2MTransportService {
// #1 // #1
LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getLwM2MClientWithReg(registration, null); LwM2MClient lwM2MClient = lwM2mInMemorySecurityStore.getLwM2MClientWithReg(registration, null);
LwM2mPath pathIds = new LwM2mPath(path); LwM2mPath pathIds = new LwM2mPath(path);
// log.warn("#0 nameDevice: [{}] resultIds: [{}] value: [{}], values: [{}] ", lwM2MClient.getDeviceName(), pathIds, value, values);
ResourceModel.Type resModelType = context.getCtxServer().getResourceModelType(registration, pathIds); ResourceModel.Type resModelType = context.getCtxServer().getResourceModelType(registration, pathIds);
ResourceValue resValueOld = lwM2MClient.getResources().get(path); ResourceValue resValueOld = lwM2MClient.getResources().get(path);
// #2 // #2
if (resValueOld.isMultiInstances() && !values.toString().equals(resValueOld.getResourceValue().toString())) { if (resValueOld.isMultiInstances() && !values.toString().equals(resValueOld.getResourceValue().toString())) {
lwM2MClient.getResources().get(path).setValues(values); lwM2MClient.getResources().get(path).setValues(values);
// ResourceValue resourceValue = new ResourceValue(values, null, true);
// lwM2MClient.getResources().put(path, resourceValue);
isChange = true; isChange = true;
} else if (!LwM2MTransportHandler.equalsResourceValue(resValueOld.getValue(), value, resModelType, pathIds)) { } else if (!LwM2MTransportHandler.equalsResourceValue(resValueOld.getValue(), value, resModelType, pathIds)) {
lwM2MClient.getResources().get(path).setValue(value); lwM2MClient.getResources().get(path).setValue(value);
// ResourceValue resourceValueOld = lwM2MClient.getResources().get(path);
// lwM2MClient.getResources().remove(resourceValueOld);
// ResourceValue resourceValue = new ResourceValue(null, value, false);
// lwM2MClient.getResources().put(path, resourceValue);
log.warn("upDateResize: [{}] [{}] [{}] [{}]", lwM2MClient.getEndPoint(), lwM2MClient.getResources().size(), value, path); log.warn("upDateResize: [{}] [{}] [{}] [{}]", lwM2MClient.getEndPoint(), lwM2MClient.getResources().size(), value, path);
isChange = true; isChange = true;
} }

View File

@ -17,10 +17,11 @@ package org.thingsboard.server.transport.lwm2m.server.client;
import lombok.Data; import lombok.Data;
import lombok.extern.slf4j.Slf4j; 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.LwM2mMultipleResource;
import org.eclipse.leshan.core.node.LwM2mObjectInstance; import org.eclipse.leshan.core.node.LwM2mObjectInstance;
import org.eclipse.leshan.core.node.LwM2mPath; import org.eclipse.leshan.core.node.LwM2mPath;
import org.eclipse.leshan.core.node.LwM2mResource;
import org.eclipse.leshan.core.node.LwM2mSingleResource;
import org.eclipse.leshan.core.response.LwM2mResponse; import org.eclipse.leshan.core.response.LwM2mResponse;
import org.eclipse.leshan.core.response.ReadResponse; import org.eclipse.leshan.core.response.ReadResponse;
import org.eclipse.leshan.server.californium.LeshanServer; import org.eclipse.leshan.server.californium.LeshanServer;
@ -35,7 +36,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@Slf4j @Slf4j
@Data @Data
@ -44,7 +44,7 @@ public class LwM2MClient implements Cloneable {
private String deviceProfileName; private String deviceProfileName;
private String endPoint; private String endPoint;
private String identity; private String identity;
private SecurityInfo info; private SecurityInfo securityInfo;
private UUID deviceUuid; private UUID deviceUuid;
private UUID sessionUuid; private UUID sessionUuid;
private UUID profileUuid; private UUID profileUuid;
@ -59,15 +59,16 @@ public class LwM2MClient implements Cloneable {
private Set<Integer> delayedRequestsId; private Set<Integer> delayedRequestsId;
private Map<String, LwM2mResponse> responses; private Map<String, LwM2mResponse> responses;
private final LwM2mValueConverterImpl converter; private final LwM2mValueConverterImpl converter;
private boolean clientUpdateValueAfterConnect;
public Object clone() throws CloneNotSupportedException { public Object clone() throws CloneNotSupportedException {
return super.clone(); return super.clone();
} }
public LwM2MClient(String endPoint, String identity, SecurityInfo info, ValidateDeviceCredentialsResponseMsg credentialsResponse, UUID profileUuid) { public LwM2MClient(String endPoint, String identity, SecurityInfo securityInfo, ValidateDeviceCredentialsResponseMsg credentialsResponse, UUID profileUuid) {
this.endPoint = endPoint; this.endPoint = endPoint;
this.identity = identity; this.identity = identity;
this.info = info; this.securityInfo = securityInfo;
this.credentialsResponse = credentialsResponse; this.credentialsResponse = credentialsResponse;
this.attributes = new ConcurrentHashMap<>(); this.attributes = new ConcurrentHashMap<>();
this.pendingRequests = ConcurrentHashMap.newKeySet(); this.pendingRequests = ConcurrentHashMap.newKeySet();
@ -98,28 +99,33 @@ public class LwM2MClient implements Cloneable {
} }
private void initValue() { private void initValue() {
this.responses.forEach((key, resp) -> { this.responses.forEach((key, lwM2mResponse) -> {
LwM2mPath pathIds = new LwM2mPath(key); LwM2mPath pathIds = new LwM2mPath(key);
if (pathIds.isObject() || pathIds.isObjectInstance() || pathIds.isResource()) { if (pathIds.isObjectInstance()) {
ObjectModel objectModel = this.lwServer.getModelProvider().getObjectModel(registration).getObjectModels().stream().filter(v -> v.id == pathIds.getObjectId()).collect(Collectors.toList()).get(0); ((LwM2mObjectInstance) ((ReadResponse) lwM2mResponse).getContent()).getResources().forEach((k, v) -> {
if (objectModel != null) { String pathRez = pathIds.toString() + "/" + k;
((LwM2mObjectInstance)((ReadResponse)resp).getContent()).getResources().forEach((k, v) -> { this.updateResourceValue(pathRez, 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));
}
}); });
} }
else if (pathIds.isResource()) {
this.updateResourceValue(pathIds.toString(), ((LwM2mResource) ((ReadResponse) lwM2mResponse).getContent()));
} }
}); });
if (this.responses.size() == 0) this.responses = new ConcurrentHashMap<>(); if (this.responses.size() == 0) this.responses = new ConcurrentHashMap<>();
} }
private void updateResourceValue(String pathRez, LwM2mResource rez) {
if (rez instanceof LwM2mMultipleResource){
this.resources.put(pathRez, new ResourceValue(rez.getValues(), null, true));
}
else if (rez instanceof LwM2mSingleResource) {
this.resources.put(pathRez, new ResourceValue(null, rez.getValue(), false));
}
}
/** /**
* if path != null * if path != null
*
* @param path * @param path
*/ */
public void onSuccessOrErrorDelayedRequests(String path) { public void onSuccessOrErrorDelayedRequests(String path) {

View File

@ -77,7 +77,7 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore {
try { try {
String registrationId = this.getByRegistrationId(endPoint, null); String registrationId = this.getByRegistrationId(endPoint, null);
return (registrationId != null && sessions.size() > 0 && sessions.get(registrationId) != null) ? return (registrationId != null && sessions.size() > 0 && sessions.get(registrationId) != null) ?
sessions.get(registrationId).getInfo() : this.addLwM2MClientToSession(endPoint); sessions.get(registrationId).getSecurityInfo() : this.addLwM2MClientToSession(endPoint);
} finally { } finally {
readLock.unlock(); readLock.unlock();
} }
@ -93,7 +93,7 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore {
readLock.lock(); readLock.lock();
try { try {
String integrationId = this.getByRegistrationId(null, identity); String integrationId = this.getByRegistrationId(null, identity);
return (integrationId != null) ? sessions.get(integrationId).getInfo() : this.addLwM2MClientToSession(identity); return (integrationId != null) ? sessions.get(integrationId).getSecurityInfo() : this.addLwM2MClientToSession(identity);
} finally { } finally {
readLock.unlock(); readLock.unlock();
} }
@ -103,7 +103,7 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore {
public Collection<SecurityInfo> getAll() { public Collection<SecurityInfo> getAll() {
readLock.lock(); readLock.lock();
try { try {
return Collections.unmodifiableCollection(this.sessions.values().stream().map(LwM2MClient::getInfo).collect(Collectors.toList())); return Collections.unmodifiableCollection(this.sessions.values().stream().map(LwM2MClient::getSecurityInfo).collect(Collectors.toList()));
} finally { } finally {
readLock.unlock(); readLock.unlock();
} }
@ -119,7 +119,7 @@ public class LwM2mInMemorySecurityStore extends InMemorySecurityStore {
LwM2MClient lwM2MClient = (sessions.get(registrationId) != null) ? sessions.get(registrationId) : null; LwM2MClient lwM2MClient = (sessions.get(registrationId) != null) ? sessions.get(registrationId) : null;
if (lwM2MClient != null) { if (lwM2MClient != null) {
if (listener != null) { if (listener != null) {
listener.securityInfoRemoved(INFOS_ARE_COMPROMISED, lwM2MClient.getInfo()); listener.securityInfoRemoved(INFOS_ARE_COMPROMISED, lwM2MClient.getSecurityInfo());
} }
sessions.remove(registrationId); sessions.remove(registrationId);
} }

View File

@ -118,6 +118,10 @@ public class LwM2MTransportConfigServer {
@Value("${transport.lwm2m.registered_pool_size:}") @Value("${transport.lwm2m.registered_pool_size:}")
private int registeredPoolSize; private int registeredPoolSize;
@Getter
@Value("${transport.lwm2m.client_update_value_after_connect:}")
private boolean clientUpdateValueAfterConnect;
@Getter @Getter
@Value("${transport.lwm2m.update_registered_pool_size:}") @Value("${transport.lwm2m.update_registered_pool_size:}")
private int updateRegisteredPoolSize; private int updateRegisteredPoolSize;