Search in sources :

Example 11 with LwM2mClient

use of org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient in project thingsboard by thingsboard.

the class DefaultLwM2mUplinkMsgHandler method updatedReg.

/**
 * if sessionInfo removed from sessions, then new registerAsyncSession
 *
 * @param registration - Registration LwM2M Client
 */
public void updatedReg(Registration registration) {
    executor.submit(() -> {
        LwM2mClient lwM2MClient = clientContext.getClientByEndpoint(registration.getEndpoint());
        try {
            log.info("[{}] [{{}] Client: update after Registration", registration.getEndpoint(), registration.getId());
            logService.log(lwM2MClient, String.format("[%s][%s] Updated registration.", registration.getId(), registration.getSocketAddress()));
            clientContext.updateRegistration(lwM2MClient, registration);
            this.reportActivityAndRegister(lwM2MClient.getSession());
        } catch (LwM2MClientStateException stateException) {
            if (LwM2MClientState.REGISTERED.equals(stateException.getState())) {
                log.info("[{}] update registration failed because client has different registration id: [{}] {}.", registration.getEndpoint(), stateException.getState(), stateException.getMessage());
            } else {
                onRegistered(registration, Collections.emptyList());
            }
        } catch (Throwable t) {
            log.error("[{}] endpoint [{}] error Unable update registration.", registration.getEndpoint(), t);
            logService.log(lwM2MClient, LOG_LWM2M_ERROR + String.format(": Client update Registration, %s", t.getMessage()));
        }
    });
}
Also used : LwM2MClientStateException(org.thingsboard.server.transport.lwm2m.server.client.LwM2MClientStateException) LwM2mClient(org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient)

Example 12 with LwM2mClient

use of org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient in project thingsboard by thingsboard.

the class LwM2MClientSerDesTest method serializeDeserialize.

@Test
public void serializeDeserialize() {
    LwM2mClient client = new LwM2mClient("nodeId", "testEndpoint");
    TransportDeviceInfo tdi = new TransportDeviceInfo();
    tdi.setPowerMode(PowerMode.PSM);
    tdi.setPsmActivityTimer(10000L);
    tdi.setPagingTransmissionWindow(2000L);
    tdi.setEdrxCycle(3000L);
    tdi.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
    tdi.setCustomerId(new CustomerId(UUID.randomUUID()));
    tdi.setDeviceId(new DeviceId(UUID.randomUUID()));
    tdi.setDeviceProfileId(new DeviceProfileId(UUID.randomUUID()));
    tdi.setDeviceName("testDevice");
    tdi.setDeviceType("testType");
    ValidateDeviceCredentialsResponse credentialsResponse = ValidateDeviceCredentialsResponse.builder().deviceInfo(tdi).build();
    client.init(credentialsResponse, UUID.randomUUID());
    Registration registration = new Registration.Builder("test", "testEndpoint", Identity.unsecure(new InetSocketAddress(1000))).supportedContentFormats().objectLinks(new Link[] { new Link("/") }).build();
    client.setRegistration(registration);
    client.setState(LwM2MClientState.REGISTERED);
    client.getSharedAttributes().put("key1", TransportProtos.TsKvProto.newBuilder().setTs(0).setKv(TransportProtos.KeyValueProto.newBuilder().setStringV("test").build()).build());
    client.getSharedAttributes().put("key2", TransportProtos.TsKvProto.newBuilder().setTs(1).setKv(TransportProtos.KeyValueProto.newBuilder().setDoubleV(1.02).build()).build());
    byte[] bytes = LwM2MClientSerDes.serialize(client);
    Assert.assertNotNull(bytes);
    LwM2mClient desClient = LwM2MClientSerDes.deserialize(bytes);
    Assert.assertEquals(client.getNodeId(), desClient.getNodeId());
    Assert.assertEquals(client.getEndpoint(), desClient.getEndpoint());
    Assert.assertEquals(client.getResources(), desClient.getResources());
    Assert.assertEquals(client.getSharedAttributes(), desClient.getSharedAttributes());
    Assert.assertEquals(client.getKeyTsLatestMap(), desClient.getKeyTsLatestMap());
    Assert.assertEquals(client.getTenantId(), desClient.getTenantId());
    Assert.assertEquals(client.getProfileId(), desClient.getProfileId());
    Assert.assertEquals(client.getDeviceId(), desClient.getDeviceId());
    Assert.assertEquals(client.getState(), desClient.getState());
    Assert.assertEquals(client.getSession(), desClient.getSession());
    Assert.assertEquals(client.getPowerMode(), desClient.getPowerMode());
    Assert.assertEquals(client.getPsmActivityTimer(), desClient.getPsmActivityTimer());
    Assert.assertEquals(client.getPagingTransmissionWindow(), desClient.getPagingTransmissionWindow());
    Assert.assertEquals(client.getEdrxCycle(), desClient.getEdrxCycle());
    Assert.assertEquals(client.getRegistration(), desClient.getRegistration());
    Assert.assertEquals(client.isAsleep(), desClient.isAsleep());
    Assert.assertEquals(client.getLastUplinkTime(), desClient.getLastUplinkTime());
    Assert.assertEquals(client.getSleepTask(), desClient.getSleepTask());
    Assert.assertEquals(client.getClientSupportContentFormats(), desClient.getClientSupportContentFormats());
    Assert.assertEquals(client.getDefaultContentFormat(), desClient.getDefaultContentFormat());
    Assert.assertEquals(client.getRetryAttempts().get(), desClient.getRetryAttempts().get());
    Assert.assertEquals(client.getLastSentRpcId(), desClient.getLastSentRpcId());
}
Also used : DeviceProfileId(org.thingsboard.server.common.data.id.DeviceProfileId) TransportDeviceInfo(org.thingsboard.server.common.transport.auth.TransportDeviceInfo) DeviceId(org.thingsboard.server.common.data.id.DeviceId) Registration(org.eclipse.leshan.server.registration.Registration) InetSocketAddress(java.net.InetSocketAddress) CustomerId(org.thingsboard.server.common.data.id.CustomerId) ValidateDeviceCredentialsResponse(org.thingsboard.server.common.transport.auth.ValidateDeviceCredentialsResponse) Link(org.eclipse.leshan.core.link.Link) LwM2mClient(org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient) Test(org.junit.Test)

Example 13 with LwM2mClient

use of org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient in project thingsboard by thingsboard.

the class DefaultLwM2MRpcRequestHandler method onToDeviceRpcRequest.

@Override
public void onToDeviceRpcRequest(TransportProtos.ToDeviceRpcRequestMsg rpcRequest, TransportProtos.SessionInfoProto sessionInfo) {
    log.debug("Received params: {}", rpcRequest.getParams());
    try {
        LwM2MOperationType operationType = LwM2MOperationType.fromType(rpcRequest.getMethodName());
        if (operationType == null) {
            this.sendErrorRpcResponse(sessionInfo, rpcRequest.getRequestId(), ResponseCode.METHOD_NOT_ALLOWED, "Unsupported operation type: " + rpcRequest.getMethodName());
            return;
        }
        LwM2mClient client = clientContext.getClientBySessionInfo(sessionInfo);
        if (client == null) {
            log.warn("Missing client for session: [{}]", sessionInfo);
            return;
        }
        if (client.getRegistration() == null) {
            this.sendErrorRpcResponse(sessionInfo, rpcRequest.getRequestId(), ResponseCode.INTERNAL_SERVER_ERROR, "Registration is empty");
            return;
        }
        UUID rpcId = new UUID(rpcRequest.getRequestIdMSB(), rpcRequest.getRequestIdLSB());
        if (rpcId.equals(client.getLastSentRpcId())) {
            log.debug("[{}]][{}] Rpc has already sent!", client.getEndpoint(), rpcId);
            return;
        }
        try {
            if (operationType.isHasObjectId()) {
                LwM2MRpcRequestHeader header = JacksonUtil.fromString(rpcRequest.getParams(), LwM2MRpcRequestHeader.class);
                String objectId = getIdFromParameters(client, header);
                switch(operationType) {
                    case READ:
                        sendReadRequest(client, rpcRequest, objectId);
                        break;
                    case OBSERVE:
                        sendObserveRequest(client, rpcRequest, objectId);
                        break;
                    case DISCOVER:
                        sendDiscoverRequest(client, rpcRequest, objectId);
                        break;
                    case EXECUTE:
                        sendExecuteRequest(client, rpcRequest, objectId);
                        break;
                    case WRITE_ATTRIBUTES:
                        sendWriteAttributesRequest(client, rpcRequest, objectId);
                        break;
                    case OBSERVE_CANCEL:
                        sendCancelObserveRequest(client, rpcRequest, objectId);
                        break;
                    case DELETE:
                        sendDeleteRequest(client, rpcRequest, objectId);
                        break;
                    case WRITE_UPDATE:
                        sendWriteUpdateRequest(client, rpcRequest, objectId);
                        break;
                    case WRITE_REPLACE:
                        sendWriteReplaceRequest(client, rpcRequest, objectId);
                        break;
                    case CREATE:
                        sendCreateRequest(client, rpcRequest, objectId);
                        break;
                    default:
                        throw new IllegalArgumentException("Unsupported operation: " + operationType.name());
                }
            } else if (operationType.isComposite()) {
                ContentFormat contentFormatComposite = this.getCompositeContentFormat(client);
                if (contentFormatComposite != null) {
                    switch(operationType) {
                        case READ_COMPOSITE:
                            sendReadCompositeRequest(client, rpcRequest, contentFormatComposite);
                            break;
                        case WRITE_COMPOSITE:
                            sendWriteCompositeRequest(client, rpcRequest, contentFormatComposite);
                            break;
                        default:
                            throw new IllegalArgumentException("Unsupported operation: " + operationType.name());
                    }
                } else {
                    this.sendErrorRpcResponse(sessionInfo, rpcRequest.getRequestId(), ResponseCode.INTERNAL_SERVER_ERROR, "This device does not support Composite Operation");
                }
            } else {
                switch(operationType) {
                    case OBSERVE_CANCEL_ALL:
                        sendCancelAllObserveRequest(client, rpcRequest);
                        break;
                    case OBSERVE_READ_ALL:
                        sendObserveAllRequest(client, rpcRequest);
                        break;
                    case DISCOVER_ALL:
                        sendDiscoverAllRequest(client, rpcRequest);
                        break;
                    default:
                        throw new IllegalArgumentException("Unsupported operation: " + operationType.name());
                }
            }
        } catch (IllegalArgumentException e) {
            this.sendErrorRpcResponse(sessionInfo, rpcRequest.getRequestId(), ResponseCode.BAD_REQUEST, e.getMessage());
        }
    } catch (Exception e) {
        log.error("[{}] Failed to send RPC: [{}]", sessionInfo, rpcRequest, e);
        this.sendErrorRpcResponse(sessionInfo, rpcRequest.getRequestId(), ResponseCode.INTERNAL_SERVER_ERROR, ExceptionUtils.getRootCauseMessage(e));
    }
}
Also used : LwM2MOperationType(org.thingsboard.server.transport.lwm2m.server.LwM2MOperationType) ContentFormat(org.eclipse.leshan.core.request.ContentFormat) UUID(java.util.UUID) JsonSyntaxException(com.google.gson.JsonSyntaxException) LwM2mClient(org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient)

Aggregations

LwM2mClient (org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient)13 LwM2mResource (org.eclipse.leshan.core.node.LwM2mResource)6 ResourceModel (org.eclipse.leshan.core.model.ResourceModel)4 LwM2MClientStateException (org.thingsboard.server.transport.lwm2m.server.client.LwM2MClientStateException)4 ArrayList (java.util.ArrayList)3 UUID (java.util.UUID)3 ObjectModel (org.eclipse.leshan.core.model.ObjectModel)3 LwM2mObject (org.eclipse.leshan.core.node.LwM2mObject)3 LwM2mObjectInstance (org.eclipse.leshan.core.node.LwM2mObjectInstance)3 Gson (com.google.gson.Gson)2 GsonBuilder (com.google.gson.GsonBuilder)2 JsonElement (com.google.gson.JsonElement)2 JsonObject (com.google.gson.JsonObject)2 Collection (java.util.Collection)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Map (java.util.Map)2 Set (java.util.Set)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 CountDownLatch (java.util.concurrent.CountDownLatch)2