Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: 重构场景联动,迁移指标函数 #384

Merged
merged 2 commits into from
Jul 28, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@
import org.jetlinks.core.device.DeviceOperator;
import org.jetlinks.core.device.DeviceProductOperator;
import org.jetlinks.core.device.DeviceRegistry;
import org.jetlinks.core.device.DeviceThingType;
import org.jetlinks.core.metadata.DeviceMetadata;
import org.jetlinks.community.relation.utils.VariableSource;
import org.jetlinks.core.things.Thing;
import org.jetlinks.core.things.ThingMetadata;
import org.jetlinks.core.things.ThingTemplate;
import org.jetlinks.core.things.ThingsRegistry;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

Expand Down Expand Up @@ -133,19 +138,19 @@ public void validate() {
DeviceSelectorProviders.getProviderNow(selector);
}

public Mono<DeviceMetadata> getDeviceMetadata(DeviceRegistry registry, String productId) {
public Mono<ThingMetadata> getDeviceMetadata(ThingsRegistry registry, String productId) {
//固定设备时使用设备的物模型
if (getSource() == Source.fixed) {
if (getSource() == Source.fixed && DeviceSelectorProviders.PROVIDER_FIXED.equals(getSelector())) {
List<SelectorValue> fixed = getSelectorValues();
if (CollectionUtils.isNotEmpty(fixed) && fixed.size() == 1) {
return registry
.getDevice(String.valueOf(fixed.get(0).getValue()))
.flatMap(DeviceOperator::getMetadata);
.getThing(DeviceThingType.device,String.valueOf(fixed.get(0).getValue()))
.flatMap(Thing::getMetadata);
}
}
return registry
.getProduct(productId)
.flatMap(DeviceProductOperator::getMetadata);
.getTemplate(DeviceThingType.device,productId)
.flatMap(ThingTemplate::getMetadata);
}
}

8 changes: 7 additions & 1 deletion jetlinks-components/things-component/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,11 @@
<artifactId>timeseries-component</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jetlinks.community</groupId>
<artifactId>gateway-component</artifactId>
<version>2.1.0-SNAPSHOT</version>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

版本号不能写死

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

好的

<scope>compile</scope>
</dependency>
</dependencies>
</project>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.jetlinks.community.things;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import reactor.function.Consumer3;

import java.util.HashSet;
import java.util.Set;

@Getter
@Setter
@ConfigurationProperties(prefix = "jetlinks.things.data")
public class ThingsDataProperties {
private Set<String> autoUpdateThingTypes = new HashSet<>();

/**
* 存储相关配置
*/
private Store store = new Store();

@Getter
@Setter
public static class Store {
//每个属性保存记录最大数量
private int maxSizeEachProperty = 8;
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
package org.jetlinks.community.things.configuration;

import lombok.Generated;
import org.hswebframework.ezorm.rdb.mapping.ReactiveRepository;
import org.jetlinks.community.things.ThingsDataProperties;
import org.jetlinks.community.things.data.*;
import org.jetlinks.community.things.impl.entity.PropertyMetricEntity;
import org.jetlinks.community.things.impl.metric.DefaultPropertyMetricManager;
import org.jetlinks.core.defaults.DeviceThingsRegistrySupport;
import org.jetlinks.core.device.DeviceRegistry;
import org.jetlinks.core.event.EventBus;
import org.jetlinks.core.things.ThingsRegistry;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

@AutoConfiguration
@Generated
@EnableConfigurationProperties(ThingsDataProperties.class)
public class ThingsConfiguration {

@Bean
Expand All @@ -34,6 +40,14 @@ public AutoRegisterThingsRegistry thingsRegistry() {
}


@Bean
public DefaultPropertyMetricManager propertyMetricManager(ThingsRegistry registry,
EventBus eventBus,
@SuppressWarnings("all")
ReactiveRepository<PropertyMetricEntity, String> repository) {
return new DefaultPropertyMetricManager(registry, eventBus, repository);
}

@Bean
@ConditionalOnBean(DeviceRegistry.class)
public DeviceThingsRegistrySupport deviceThingsRegistrySupport(DeviceRegistry registry) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package org.jetlinks.community.things.impl.entity;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import org.hswebframework.ezorm.rdb.mapping.annotation.DefaultValue;
import org.hswebframework.web.api.crud.entity.GenericEntity;
import org.hswebframework.web.api.crud.entity.RecordCreationEntity;
import org.hswebframework.web.crud.annotation.EnableEntityEvent;
import org.hswebframework.web.crud.generator.Generators;
import org.hswebframework.web.utils.DigestUtils;
import org.jetlinks.community.PropertyMetric;

import javax.persistence.Column;
import javax.persistence.Table;

@Getter
@Setter
@Table(name = "thing_property_metric")
@EnableEntityEvent
public class PropertyMetricEntity extends GenericEntity<String> implements RecordCreationEntity {

@Schema(description = "物类型,如: device")
@Column(length = 32, nullable = false, updatable = false)
private String thingType;

@Schema(description = "物ID,如: 设备ID")
@Column(length = 64, nullable = false, updatable = false)
private String thingId;

@Schema(description = "属性标识")
@Column(length = 64, nullable = false, updatable = false)
private String property;

@Schema(description = "指标标识")
@Column(length = 64, nullable = false, updatable = false)
private String metric;

@Schema(description = "指标名称")
@Column(length = 64)
private String metricName;

@Schema(description = "指标值")
@Column(length = 256, nullable = false)
private String value;

@Schema(description = "是否为范围值")
@Column(nullable = false)
@DefaultValue("false")
private Boolean range;

@Schema(description = "创建人ID")
@Column(length = 64, nullable = false, updatable = false)
private String creatorId;

@Schema(description = "创建时间")
@Column(nullable = false, updatable = false)
@DefaultValue(generator = Generators.CURRENT_TIME)
private Long createTime;

public void genericId(){
setId(genericId(
thingType,thingId,property,metric
));
}
public static String genericId(String thingType, String thingId,String property, String metric) {
return DigestUtils.md5Hex(String.join("|", thingType, thingId, property, metric));
}

public PropertyMetric toMetric(){
PropertyMetric propertyMetric=new PropertyMetric();
propertyMetric.setId(metric);
propertyMetric.setValue(value);
propertyMetric.setRange(range);
propertyMetric.setName(metricName);
return propertyMetric;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
package org.jetlinks.community.things.impl.metric;

import org.hswebframework.ezorm.rdb.mapping.ReactiveRepository;
import org.hswebframework.ezorm.rdb.mapping.defaults.SaveResult;
import org.hswebframework.web.crud.events.EntityCreatedEvent;
import org.hswebframework.web.crud.events.EntityDeletedEvent;
import org.hswebframework.web.crud.events.EntityModifyEvent;
import org.hswebframework.web.crud.events.EntitySavedEvent;
import org.jetlinks.core.event.EventBus;
import org.jetlinks.core.event.Subscription;
import org.jetlinks.core.things.Thing;
import org.jetlinks.core.things.ThingId;
import org.jetlinks.core.things.ThingTemplate;
import org.jetlinks.core.things.ThingsRegistry;
import org.jetlinks.community.PropertyMetadataConstants;
import org.jetlinks.community.PropertyMetric;
import org.jetlinks.community.gateway.annotation.Subscribe;
import org.jetlinks.community.things.impl.entity.PropertyMetricEntity;
import org.jetlinks.community.things.metric.AbstractPropertyMetricManager;
import org.springframework.context.event.EventListener;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;

public class DefaultPropertyMetricManager extends AbstractPropertyMetricManager {

private final EventBus eventBus;

private final ReactiveRepository<PropertyMetricEntity, String> repository;

public DefaultPropertyMetricManager(ThingsRegistry registry,
EventBus eventBus,
ReactiveRepository<PropertyMetricEntity, String> repository) {
super(registry);
this.eventBus = eventBus;
this.repository = repository;
}

public Flux<PropertyMetric> getPropertyMetrics(String thingType,
String thingId,
String property) {
return Mono
.zip(
//数据库中记录的
repository
.createQuery()
.where(PropertyMetricEntity::getThingType, thingType)
.and(PropertyMetricEntity::getThingId, thingId)
.and(PropertyMetricEntity::getProperty, property)
.fetch()
.map(PropertyMetricEntity::toMetric)
.collectMap(PropertyMetric::getId),
//物模型中配置的
registry
.getThing(thingType, thingId)
.flatMap(Thing::getTemplate)
.flatMap(ThingTemplate::getMetadata)
.flatMapIterable(metadata -> metadata
.getProperty(property)
.map(PropertyMetadataConstants.Metrics::getMetrics)
.orElse(Collections.emptyList()))
.collectMap(PropertyMetric::getId, Function.identity(), LinkedHashMap::new),
(exists, inMetadata) -> {
for (Map.Entry<String, PropertyMetric> entry : exists.entrySet()) {
String metric = entry.getKey();
PropertyMetric independent = entry.getValue();
PropertyMetric fromMetadata = inMetadata.get(metric);
if (fromMetadata == null) {
inMetadata.put(metric, independent);
continue;
}
fromMetadata.setValue(independent.getValue());
}
return Flux.fromIterable(inMetadata.values());
})
.flatMapMany(Function.identity());
}

public Mono<SaveResult> savePropertyMetrics(String thingType,
String thingId,
String property,
Flux<PropertyMetric> metrics) {
return metrics
.map(metric -> {
PropertyMetricEntity entity = new PropertyMetricEntity();
entity.setThingId(thingId);
entity.setThingType(thingType);
entity.setMetric(metric.getId());
entity.setMetricName(metric.getName());
entity.setProperty(property);
entity.setValue(String.valueOf(metric.getValue()));
entity.setRange(metric.isRange());
entity.genericId();
return entity;
})
.as(repository::save);

}

@Override
protected Mono<PropertyMetric> loadPropertyMetric(ThingId thingId,
String property,
String metric) {

return repository
.findById(PropertyMetricEntity.genericId(thingId.getType(), thingId.getId(), property, metric))
.map(PropertyMetricEntity::toMetric);
}

@EventListener
public void handleEntityChanged(EntityModifyEvent<PropertyMetricEntity> event) {
event.async(
Flux.fromIterable(event.getAfter())
.flatMap(this::handleMetricChangedEvent)
);
}

@EventListener
public void handleEntityChanged(EntityCreatedEvent<PropertyMetricEntity> event) {
event.async(
Flux.fromIterable(event.getEntity())
.flatMap(this::handleMetricChangedEvent)
);
}

@EventListener
public void handleEntityChanged(EntityDeletedEvent<PropertyMetricEntity> event) {
event.async(
Flux.fromIterable(event.getEntity())
.flatMap(this::handleMetricChangedEvent)
);
}

@EventListener
public void handleEntityChanged(EntitySavedEvent<PropertyMetricEntity> event) {
event.async(
Flux.fromIterable(event.getEntity())
.flatMap(this::handleMetricChangedEvent)
);
}

@Subscribe(value = "/_sys/thing-property-metric/clear-cache", features = Subscription.Feature.broker)
public Mono<Void> handleMetricChangedEvent(CacheKey key) {
cache.remove(key);
return Mono.empty();
}

private Mono<Void> handleMetricChangedEvent(PropertyMetricEntity entity) {
CacheKey key = CacheKey.of(ThingId.of(entity.getThingType(), entity.getThingId()), entity.getProperty(), entity.getMetric());
cache.remove(key);
return eventBus
.publish("/_sys/thing-property-metric/clear-cache", key)
.then();
}
}
Loading