Search in sources :

Example 1 with DeviceProfile

use of org.thingsboard.server.common.data.DeviceProfile in project thingsboard by thingsboard.

the class DefaultTransportApiService method getDeviceInfo.

private ListenableFuture<TransportApiResponseMsg> getDeviceInfo(DeviceCredentials credentials) {
    return Futures.transform(deviceService.findDeviceByIdAsync(TenantId.SYS_TENANT_ID, credentials.getDeviceId()), device -> {
        if (device == null) {
            log.trace("[{}] Failed to lookup device by id", credentials.getDeviceId());
            return getEmptyTransportApiResponse();
        }
        try {
            ValidateDeviceCredentialsResponseMsg.Builder builder = ValidateDeviceCredentialsResponseMsg.newBuilder();
            builder.setDeviceInfo(getDeviceInfoProto(device));
            DeviceProfile deviceProfile = deviceProfileCache.get(device.getTenantId(), device.getDeviceProfileId());
            if (deviceProfile != null) {
                builder.setProfileBody(ByteString.copyFrom(dataDecodingEncodingService.encode(deviceProfile)));
            } else {
                log.warn("[{}] Failed to find device profile [{}] for device. ", device.getId(), device.getDeviceProfileId());
            }
            if (!StringUtils.isEmpty(credentials.getCredentialsValue())) {
                builder.setCredentialsBody(credentials.getCredentialsValue());
            }
            return TransportApiResponseMsg.newBuilder().setValidateCredResponseMsg(builder.build()).build();
        } catch (JsonProcessingException e) {
            log.warn("[{}] Failed to lookup device by id", credentials.getDeviceId(), e);
            return getEmptyTransportApiResponse();
        }
    }, MoreExecutors.directExecutor());
}
Also used : DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) ValidateDeviceCredentialsResponseMsg(org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceCredentialsResponseMsg) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 2 with DeviceProfile

use of org.thingsboard.server.common.data.DeviceProfile in project thingsboard by thingsboard.

the class DefaultTransportApiService method handle.

private ListenableFuture<TransportApiResponseMsg> handle(GetEntityProfileRequestMsg requestMsg) {
    EntityType entityType = EntityType.valueOf(requestMsg.getEntityType());
    UUID entityUuid = new UUID(requestMsg.getEntityIdMSB(), requestMsg.getEntityIdLSB());
    GetEntityProfileResponseMsg.Builder builder = GetEntityProfileResponseMsg.newBuilder();
    if (entityType.equals(EntityType.DEVICE_PROFILE)) {
        DeviceProfileId deviceProfileId = new DeviceProfileId(entityUuid);
        DeviceProfile deviceProfile = deviceProfileCache.find(deviceProfileId);
        builder.setData(ByteString.copyFrom(dataDecodingEncodingService.encode(deviceProfile)));
    } else if (entityType.equals(EntityType.TENANT)) {
        TenantId tenantId = TenantId.fromUUID(entityUuid);
        TenantProfile tenantProfile = tenantProfileCache.get(tenantId);
        ApiUsageState state = apiUsageStateService.getApiUsageState(tenantId);
        builder.setData(ByteString.copyFrom(dataDecodingEncodingService.encode(tenantProfile)));
        builder.setApiState(ByteString.copyFrom(dataDecodingEncodingService.encode(state)));
    } else {
        throw new RuntimeException("Invalid entity profile request: " + entityType);
    }
    return Futures.immediateFuture(TransportApiResponseMsg.newBuilder().setEntityProfileResponseMsg(builder).build());
}
Also used : EntityType(org.thingsboard.server.common.data.EntityType) DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) TenantId(org.thingsboard.server.common.data.id.TenantId) DeviceProfileId(org.thingsboard.server.common.data.id.DeviceProfileId) ApiUsageState(org.thingsboard.server.common.data.ApiUsageState) TenantProfile(org.thingsboard.server.common.data.TenantProfile) UUID(java.util.UUID) GetEntityProfileResponseMsg(org.thingsboard.server.gen.transport.TransportProtos.GetEntityProfileResponseMsg)

Example 3 with DeviceProfile

use of org.thingsboard.server.common.data.DeviceProfile in project thingsboard by thingsboard.

the class DefaultTransportApiService method handle.

private ListenableFuture<TransportApiResponseMsg> handle(GetOrCreateDeviceFromGatewayRequestMsg requestMsg) {
    DeviceId gatewayId = new DeviceId(new UUID(requestMsg.getGatewayIdMSB(), requestMsg.getGatewayIdLSB()));
    ListenableFuture<Device> gatewayFuture = deviceService.findDeviceByIdAsync(TenantId.SYS_TENANT_ID, gatewayId);
    return Futures.transform(gatewayFuture, gateway -> {
        Lock deviceCreationLock = deviceCreationLocks.computeIfAbsent(requestMsg.getDeviceName(), id -> new ReentrantLock());
        deviceCreationLock.lock();
        try {
            Device device = deviceService.findDeviceByTenantIdAndName(gateway.getTenantId(), requestMsg.getDeviceName());
            if (device == null) {
                TenantId tenantId = gateway.getTenantId();
                device = new Device();
                device.setTenantId(tenantId);
                device.setName(requestMsg.getDeviceName());
                device.setType(requestMsg.getDeviceType());
                device.setCustomerId(gateway.getCustomerId());
                DeviceProfile deviceProfile = deviceProfileCache.findOrCreateDeviceProfile(gateway.getTenantId(), requestMsg.getDeviceType());
                device.setDeviceProfileId(deviceProfile.getId());
                ObjectNode additionalInfo = JacksonUtil.newObjectNode();
                additionalInfo.put(DataConstants.LAST_CONNECTED_GATEWAY, gatewayId.toString());
                device.setAdditionalInfo(additionalInfo);
                Device savedDevice = deviceService.saveDevice(device);
                tbClusterService.onDeviceUpdated(savedDevice, null);
                device = savedDevice;
                relationService.saveRelationAsync(TenantId.SYS_TENANT_ID, new EntityRelation(gateway.getId(), device.getId(), "Created"));
                TbMsgMetaData metaData = new TbMsgMetaData();
                CustomerId customerId = gateway.getCustomerId();
                if (customerId != null && !customerId.isNullUid()) {
                    metaData.putValue("customerId", customerId.toString());
                }
                metaData.putValue("gatewayId", gatewayId.toString());
                DeviceId deviceId = device.getId();
                ObjectNode entityNode = mapper.valueToTree(device);
                TbMsg tbMsg = TbMsg.newMsg(DataConstants.ENTITY_CREATED, deviceId, customerId, metaData, TbMsgDataType.JSON, mapper.writeValueAsString(entityNode));
                tbClusterService.pushMsgToRuleEngine(tenantId, deviceId, tbMsg, null);
            } else {
                JsonNode deviceAdditionalInfo = device.getAdditionalInfo();
                if (deviceAdditionalInfo == null) {
                    deviceAdditionalInfo = JacksonUtil.newObjectNode();
                }
                if (deviceAdditionalInfo.isObject() && (!deviceAdditionalInfo.has(DataConstants.LAST_CONNECTED_GATEWAY) || !gatewayId.toString().equals(deviceAdditionalInfo.get(DataConstants.LAST_CONNECTED_GATEWAY).asText()))) {
                    ObjectNode newDeviceAdditionalInfo = (ObjectNode) deviceAdditionalInfo;
                    newDeviceAdditionalInfo.put(DataConstants.LAST_CONNECTED_GATEWAY, gatewayId.toString());
                    Device savedDevice = deviceService.saveDevice(device);
                    tbClusterService.onDeviceUpdated(savedDevice, device);
                }
            }
            GetOrCreateDeviceFromGatewayResponseMsg.Builder builder = GetOrCreateDeviceFromGatewayResponseMsg.newBuilder().setDeviceInfo(getDeviceInfoProto(device));
            DeviceProfile deviceProfile = deviceProfileCache.get(device.getTenantId(), device.getDeviceProfileId());
            if (deviceProfile != null) {
                builder.setProfileBody(ByteString.copyFrom(dataDecodingEncodingService.encode(deviceProfile)));
            } else {
                log.warn("[{}] Failed to find device profile [{}] for device. ", device.getId(), device.getDeviceProfileId());
            }
            return TransportApiResponseMsg.newBuilder().setGetOrCreateDeviceResponseMsg(builder.build()).build();
        } catch (JsonProcessingException e) {
            log.warn("[{}] Failed to lookup device by gateway id and name: [{}]", gatewayId, requestMsg.getDeviceName(), e);
            throw new RuntimeException(e);
        } finally {
            deviceCreationLock.unlock();
        }
    }, dbCallbackExecutorService);
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DeviceId(org.thingsboard.server.common.data.id.DeviceId) Device(org.thingsboard.server.common.data.Device) JsonNode(com.fasterxml.jackson.databind.JsonNode) GetOrCreateDeviceFromGatewayResponseMsg(org.thingsboard.server.gen.transport.TransportProtos.GetOrCreateDeviceFromGatewayResponseMsg) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) CustomerId(org.thingsboard.server.common.data.id.CustomerId) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) TenantId(org.thingsboard.server.common.data.id.TenantId) UUID(java.util.UUID) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) TbMsg(org.thingsboard.server.common.msg.TbMsg)

Example 4 with DeviceProfile

use of org.thingsboard.server.common.data.DeviceProfile in project thingsboard by thingsboard.

the class DefaultTransportApiService method handle.

private ListenableFuture<TransportApiResponseMsg> handle(TransportProtos.GetOtaPackageRequestMsg requestMsg) {
    TenantId tenantId = TenantId.fromUUID(new UUID(requestMsg.getTenantIdMSB(), requestMsg.getTenantIdLSB()));
    DeviceId deviceId = new DeviceId(new UUID(requestMsg.getDeviceIdMSB(), requestMsg.getDeviceIdLSB()));
    OtaPackageType otaPackageType = OtaPackageType.valueOf(requestMsg.getType());
    Device device = deviceService.findDeviceById(tenantId, deviceId);
    if (device == null) {
        return getEmptyTransportApiResponseFuture();
    }
    OtaPackageId otaPackageId = OtaPackageUtil.getOtaPackageId(device, otaPackageType);
    if (otaPackageId == null) {
        DeviceProfile deviceProfile = deviceProfileCache.find(device.getDeviceProfileId());
        otaPackageId = OtaPackageUtil.getOtaPackageId(deviceProfile, otaPackageType);
    }
    TransportProtos.GetOtaPackageResponseMsg.Builder builder = TransportProtos.GetOtaPackageResponseMsg.newBuilder();
    if (otaPackageId == null) {
        builder.setResponseStatus(TransportProtos.ResponseStatus.NOT_FOUND);
    } else {
        OtaPackageInfo otaPackageInfo = otaPackageService.findOtaPackageInfoById(tenantId, otaPackageId);
        if (otaPackageInfo == null) {
            builder.setResponseStatus(TransportProtos.ResponseStatus.NOT_FOUND);
        } else if (otaPackageInfo.hasUrl()) {
            builder.setResponseStatus(TransportProtos.ResponseStatus.FAILURE);
            log.trace("[{}] Can`t send OtaPackage with URL data!", otaPackageInfo.getId());
        } else {
            builder.setResponseStatus(TransportProtos.ResponseStatus.SUCCESS);
            builder.setOtaPackageIdMSB(otaPackageId.getId().getMostSignificantBits());
            builder.setOtaPackageIdLSB(otaPackageId.getId().getLeastSignificantBits());
            builder.setType(otaPackageInfo.getType().name());
            builder.setTitle(otaPackageInfo.getTitle());
            builder.setVersion(otaPackageInfo.getVersion());
            builder.setFileName(otaPackageInfo.getFileName());
            builder.setContentType(otaPackageInfo.getContentType());
            if (!otaPackageDataCache.has(otaPackageId.toString())) {
                OtaPackage otaPackage = otaPackageService.findOtaPackageById(tenantId, otaPackageId);
                otaPackageDataCache.put(otaPackageId.toString(), otaPackage.getData().array());
            }
        }
    }
    return Futures.immediateFuture(TransportApiResponseMsg.newBuilder().setOtaPackageResponseMsg(builder.build()).build());
}
Also used : DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) TenantId(org.thingsboard.server.common.data.id.TenantId) OtaPackageType(org.thingsboard.server.common.data.ota.OtaPackageType) DeviceId(org.thingsboard.server.common.data.id.DeviceId) Device(org.thingsboard.server.common.data.Device) OtaPackage(org.thingsboard.server.common.data.OtaPackage) OtaPackageId(org.thingsboard.server.common.data.id.OtaPackageId) OtaPackageInfo(org.thingsboard.server.common.data.OtaPackageInfo) UUID(java.util.UUID)

Example 5 with DeviceProfile

use of org.thingsboard.server.common.data.DeviceProfile in project thingsboard by thingsboard.

the class SnmpTransportContext method establishDeviceSession.

private void establishDeviceSession(Device device) {
    if (device == null)
        return;
    log.info("Establishing SNMP session for device {}", device.getId());
    DeviceProfileId deviceProfileId = device.getDeviceProfileId();
    DeviceProfile deviceProfile = deviceProfileCache.get(deviceProfileId);
    DeviceCredentials credentials = protoEntityService.getDeviceCredentialsByDeviceId(device.getId());
    if (credentials.getCredentialsType() != DeviceCredentialsType.ACCESS_TOKEN) {
        log.warn("[{}] Expected credentials type is {} but found {}", device.getId(), DeviceCredentialsType.ACCESS_TOKEN, credentials.getCredentialsType());
        return;
    }
    SnmpDeviceProfileTransportConfiguration profileTransportConfiguration = (SnmpDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration();
    SnmpDeviceTransportConfiguration deviceTransportConfiguration = (SnmpDeviceTransportConfiguration) device.getDeviceData().getTransportConfiguration();
    DeviceSessionContext deviceSessionContext;
    try {
        deviceSessionContext = new DeviceSessionContext(device, deviceProfile, credentials.getCredentialsId(), profileTransportConfiguration, deviceTransportConfiguration, this);
        registerSessionMsgListener(deviceSessionContext);
    } catch (Exception e) {
        log.error("Failed to establish session for SNMP device {}: {}", device.getId(), e.toString());
        return;
    }
    sessions.put(device.getId(), deviceSessionContext);
    snmpTransportService.createQueryingTasks(deviceSessionContext);
    log.info("Established SNMP device session for device {}", device.getId());
}
Also used : SnmpDeviceProfileTransportConfiguration(org.thingsboard.server.common.data.device.profile.SnmpDeviceProfileTransportConfiguration) DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) SnmpDeviceTransportConfiguration(org.thingsboard.server.common.data.device.data.SnmpDeviceTransportConfiguration) DeviceProfileId(org.thingsboard.server.common.data.id.DeviceProfileId) DeviceSessionContext(org.thingsboard.server.transport.snmp.session.DeviceSessionContext) DeviceCredentials(org.thingsboard.server.common.data.security.DeviceCredentials)

Aggregations

DeviceProfile (org.thingsboard.server.common.data.DeviceProfile)110 Test (org.junit.Test)48 Device (org.thingsboard.server.common.data.Device)30 DeviceProfileData (org.thingsboard.server.common.data.device.profile.DeviceProfileData)26 List (java.util.List)20 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)19 TbMsg (org.thingsboard.server.common.msg.TbMsg)19 DeviceProfileAlarm (org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm)18 TbMsgMetaData (org.thingsboard.server.common.msg.TbMsgMetaData)18 AlarmConditionFilterKey (org.thingsboard.server.common.data.device.profile.AlarmConditionFilterKey)17 AlarmRule (org.thingsboard.server.common.data.device.profile.AlarmRule)17 AlarmCondition (org.thingsboard.server.common.data.device.profile.AlarmCondition)16 AlarmConditionFilter (org.thingsboard.server.common.data.device.profile.AlarmConditionFilter)16 NumericFilterPredicate (org.thingsboard.server.common.data.query.NumericFilterPredicate)16 DynamicValue (org.thingsboard.server.common.data.query.DynamicValue)14 DeviceProfileId (org.thingsboard.server.common.data.id.DeviceProfileId)13 AttributeKvEntry (org.thingsboard.server.common.data.kv.AttributeKvEntry)13 AttributeKvCompositeKey (org.thingsboard.server.dao.model.sql.AttributeKvCompositeKey)13 AttributeKvEntity (org.thingsboard.server.dao.model.sql.AttributeKvEntity)13 UUID (java.util.UUID)12