Search in sources :

Example 1 with AGENT_LINK

use of org.openremote.model.value.MetaItemType.AGENT_LINK in project openremote by openremote.

the class AgentService method startAgent.

protected void startAgent(Agent<?, ?, ?> agent) {
    withLock(getClass().getSimpleName() + "::startAgent", () -> {
        Protocol<?> protocol = null;
        try {
            protocol = agent.getProtocolInstance();
            protocolInstanceMap.put(agent.getId(), protocol);
            LOG.fine("Starting protocol instance: " + protocol);
            protocol.start(container);
            LOG.fine("Started protocol instance:" + protocol);
            LOG.finer("Linking attributes to protocol instance: " + protocol);
            // Get all assets that have attributes with agent link meta for this agent
            List<Asset<?>> assets = assetStorageService.findAll(new AssetQuery().attributes(new AttributePredicate().meta(new NameValuePredicate(AGENT_LINK, new StringPredicate(agent.getId()), false, new NameValuePredicate.Path("id")))));
            LOG.finer("Found '" + assets.size() + "' asset(s) with attributes linked to this protocol instance: " + protocol);
            assets.forEach(asset -> getGroupedAgentLinkAttributes(asset.getAttributes().stream(), assetAttribute -> assetAttribute.getMetaValue(AGENT_LINK).map(agentLink -> agentLink.getId().equals(agent.getId())).orElse(false)).forEach((agnt, attributes) -> linkAttributes(agnt, asset.getId(), attributes)));
        } catch (Exception e) {
            if (protocol != null) {
                try {
                    protocol.stop(container);
                } catch (Exception ignored) {
                }
            }
            protocolInstanceMap.remove(agent.getId());
            LOG.log(Level.SEVERE, "Failed to start protocol instance for agent: " + agent, e);
            sendAttributeEvent(new AttributeEvent(agent.getId(), Agent.STATUS.getName(), ConnectionStatus.ERROR));
        }
    });
}
Also used : Protocol(org.openremote.model.asset.agent.Protocol) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException) AssetProcessingService(org.openremote.manager.asset.AssetProcessingService) ASSET_QUEUE(org.openremote.manager.asset.AssetProcessingService.ASSET_QUEUE) ProtocolInstanceDiscovery(org.openremote.model.protocol.ProtocolInstanceDiscovery) ACTUATOR_TOPIC(org.openremote.model.asset.agent.Protocol.ACTUATOR_TOPIC) AgentLink(org.openremote.model.asset.agent.AgentLink) Future(java.util.concurrent.Future) TextUtil(org.openremote.model.util.TextUtil) Attribute.getAddedOrModifiedAttributes(org.openremote.model.attribute.Attribute.getAddedOrModifiedAttributes) AssetTreeNode(org.openremote.model.asset.AssetTreeNode) Predicate(java.util.function.Predicate) ProtocolAssetDiscovery(org.openremote.model.protocol.ProtocolAssetDiscovery) ContainerService(org.openremote.model.ContainerService) AttributePredicate(org.openremote.model.query.filter.AttributePredicate) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Container(org.openremote.model.Container) Stream(java.util.stream.Stream) StringPredicate(org.openremote.model.query.filter.StringPredicate) RouteBuilder(org.apache.camel.builder.RouteBuilder) PERSISTENCE_TOPIC(org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC) org.openremote.model.attribute(org.openremote.model.attribute) Agent(org.openremote.model.asset.agent.Agent) PathPredicate(org.openremote.model.query.filter.PathPredicate) GatewayService(org.openremote.manager.gateway.GatewayService) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) AssetStorageService(org.openremote.manager.asset.AssetStorageService) GatewayService.isNotForGateway(org.openremote.manager.gateway.GatewayService.isNotForGateway) java.util(java.util) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) Level(java.util.logging.Level) GlobalLock.withLockReturning(org.openremote.container.concurrent.GlobalLock.withLockReturning) AGENT_LINK(org.openremote.model.value.MetaItemType.AGENT_LINK) Collectors.mapping(java.util.stream.Collectors.mapping) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) NameValuePredicate(org.openremote.model.query.filter.NameValuePredicate) ManagerWebService(org.openremote.manager.web.ManagerWebService) PersistenceEvent(org.openremote.model.PersistenceEvent) MessageBrokerService(org.openremote.container.message.MessageBrokerService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) Asset(org.openremote.model.asset.Asset) AssetQuery(org.openremote.model.query.AssetQuery) Pair(org.openremote.model.util.Pair) ProtocolAssetService(org.openremote.agent.protocol.ProtocolAssetService) EntityManager(javax.persistence.EntityManager) HEADER_SOURCE(org.openremote.model.attribute.AttributeEvent.HEADER_SOURCE) Consumer(java.util.function.Consumer) SENSOR_QUEUE(org.openremote.model.asset.agent.Protocol.SENSOR_QUEUE) ClientEventService(org.openremote.manager.event.ClientEventService) ProtocolAssetImport(org.openremote.model.protocol.ProtocolAssetImport) Collectors.toList(java.util.stream.Collectors.toList) TimerService(org.openremote.container.timer.TimerService) AssetUpdateProcessor(org.openremote.manager.asset.AssetUpdateProcessor) PersistenceService.isPersistenceEventForEntityType(org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType) Source(org.openremote.model.attribute.AttributeEvent.Source) StringPredicate(org.openremote.model.query.filter.StringPredicate) AssetQuery(org.openremote.model.query.AssetQuery) Asset(org.openremote.model.asset.Asset) NameValuePredicate(org.openremote.model.query.filter.NameValuePredicate) AttributePredicate(org.openremote.model.query.filter.AttributePredicate) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException)

Example 2 with AGENT_LINK

use of org.openremote.model.value.MetaItemType.AGENT_LINK in project openremote by openremote.

the class AbstractVelbusProtocol method startAssetImport.

/* ProtocolAssetImport */
@Override
public Future<Void> startAssetImport(byte[] fileData, Consumer<AssetTreeNode[]> assetConsumer) {
    return executorService.submit(() -> {
        Document xmlDoc;
        try {
            String xmlStr = new String(fileData, StandardCharsets.UTF_8);
            LOG.info("Parsing VELBUS project file");
            xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xmlStr)));
        } catch (Exception e) {
            LOG.log(Level.WARNING, "Failed to convert VELBUS project file into XML", e);
            return;
        }
        xmlDoc.getDocumentElement().normalize();
        NodeList modules = xmlDoc.getElementsByTagName("Module");
        LOG.info("Found " + modules.getLength() + " module(s)");
        List<Asset<?>> devices = new ArrayList<>(modules.getLength());
        for (int i = 0; i < modules.getLength(); i++) {
            Element module = (Element) modules.item(i);
            // TODO: Process memory map and add
            Optional<VelbusDeviceType> deviceType = EnumUtil.enumFromString(VelbusDeviceType.class, module.getAttribute("type").replaceAll("-", ""));
            if (!deviceType.isPresent()) {
                LOG.info("Module device type '" + module.getAttribute("type") + "' is not supported so ignoring");
                continue;
            }
            String[] addresses = module.getAttribute("address").split(",");
            int baseAddress = Integer.parseInt(addresses[0], 16);
            String build = module.getAttribute("build");
            String serial = module.getAttribute("serial");
            String name = module.getElementsByTagName("Caption").item(0).getTextContent();
            name = isNullOrEmpty(name) ? deviceType.toString() : name;
            // TODO: Use device specific asset types
            Asset<?> device = new ThingAsset(name);
            device.addAttributes(new Attribute<>("build", ValueType.TEXT, build).addMeta(new MetaItem<>(MetaItemType.LABEL, "Build"), new MetaItem<>(MetaItemType.READ_ONLY, true)), new Attribute<>("serialNumber", ValueType.TEXT, serial).addMeta(new MetaItem<>(MetaItemType.LABEL, "Serial No"), new MetaItem<>(MetaItemType.READ_ONLY, true)));
            device.addAttributes(deviceType.flatMap(type -> Optional.ofNullable(type.getFeatureProcessors()).map(processors -> Arrays.stream(processors).flatMap(processor -> processor.getPropertyDescriptors(type).stream().map(descriptor -> {
                VelbusAgentLink agentLink = new VelbusAgentLink(agent.getId(), baseAddress, descriptor.getLinkName());
                Attribute<?> attribute = new Attribute<>(descriptor.getName(), descriptor.getAttributeValueDescriptor()).addMeta(new MetaItem<>(AGENT_LINK, agentLink), new MetaItem<>(MetaItemType.LABEL, descriptor.getDisplayName()));
                if (descriptor.isReadOnly()) {
                    attribute.addMeta(new MetaItem<>(MetaItemType.READ_ONLY, true));
                }
                return attribute;
            })).toArray(Attribute<?>[]::new))).orElse(new Attribute<?>[0]));
            devices.add(device);
        }
        assetConsumer.accept(devices.stream().map(AssetTreeNode::new).toArray(AssetTreeNode[]::new));
    }, null);
}
Also used : java.util(java.util) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) ThingAsset(org.openremote.model.asset.impl.ThingAsset) VelbusDeviceType(org.openremote.agent.protocol.velbus.device.VelbusDeviceType) Level(java.util.logging.Level) AGENT_LINK(org.openremote.model.value.MetaItemType.AGENT_LINK) Future(java.util.concurrent.Future) Document(org.w3c.dom.Document) SyslogCategory(org.openremote.model.syslog.SyslogCategory) IOClient(org.openremote.agent.protocol.io.IOClient) InputSource(org.xml.sax.InputSource) AssetTreeNode(org.openremote.model.asset.AssetTreeNode) NodeList(org.w3c.dom.NodeList) ValueType(org.openremote.model.value.ValueType) Asset(org.openremote.model.asset.Asset) MetaItemType(org.openremote.model.value.MetaItemType) EnumUtil(org.openremote.model.util.EnumUtil) Logger(java.util.logging.Logger) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) StandardCharsets(java.nio.charset.StandardCharsets) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) Consumer(java.util.function.Consumer) ProtocolAssetImport(org.openremote.model.protocol.ProtocolAssetImport) Element(org.w3c.dom.Element) StringReader(java.io.StringReader) org.openremote.model.attribute(org.openremote.model.attribute) AgentLink.getOrThrowAgentLinkProperty(org.openremote.model.asset.agent.AgentLink.getOrThrowAgentLinkProperty) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TextUtil.isNullOrEmpty(org.openremote.model.util.TextUtil.isNullOrEmpty) InputSource(org.xml.sax.InputSource) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) VelbusDeviceType(org.openremote.agent.protocol.velbus.device.VelbusDeviceType) Document(org.w3c.dom.Document) AssetTreeNode(org.openremote.model.asset.AssetTreeNode) StringReader(java.io.StringReader) ThingAsset(org.openremote.model.asset.impl.ThingAsset) Asset(org.openremote.model.asset.Asset) ThingAsset(org.openremote.model.asset.impl.ThingAsset)

Aggregations

java.util (java.util)2 Future (java.util.concurrent.Future)2 Consumer (java.util.function.Consumer)2 Level (java.util.logging.Level)2 Logger (java.util.logging.Logger)2 Container (org.openremote.model.Container)2 Asset (org.openremote.model.asset.Asset)2 AssetTreeNode (org.openremote.model.asset.AssetTreeNode)2 ConnectionStatus (org.openremote.model.asset.agent.ConnectionStatus)2 org.openremote.model.attribute (org.openremote.model.attribute)2 ProtocolAssetImport (org.openremote.model.protocol.ProtocolAssetImport)2 AGENT_LINK (org.openremote.model.value.MetaItemType.AGENT_LINK)2 StringReader (java.io.StringReader)1 StandardCharsets (java.nio.charset.StandardCharsets)1 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)1 Predicate (java.util.function.Predicate)1 Collectors (java.util.stream.Collectors)1 Collectors.mapping (java.util.stream.Collectors.mapping)1 Collectors.toList (java.util.stream.Collectors.toList)1 Stream (java.util.stream.Stream)1