Search in sources :

Example 11 with AssetAttribute

use of org.openremote.model.asset.AssetAttribute in project openremote by openremote.

the class ManagerDemoAgentSetup method onStart.

@Override
public void onStart() throws Exception {
    KeycloakDemoSetup keycloakDemoSetup = setupService.getTaskOfType(KeycloakDemoSetup.class);
    Tenant masterTenant = keycloakDemoSetup.masterTenant;
    masterRealmId = masterTenant.getId();
    ServerAsset agent = new ServerAsset("Demo Agent", AGENT);
    agent.setRealmId(masterRealmId);
    agent = assetStorageService.merge(agent);
    if (knx) {
        LOG.info("Enable KNX demo protocol configuration, gateway/local IP: " + knxGatewayIp + "/" + knxLocalIp);
        agent.addAttributes(initProtocolConfiguration(new AssetAttribute("knxConfig"), KNXProtocol.PROTOCOL_NAME).addMeta(new MetaItem(KNXProtocol.META_KNX_GATEWAY_IP, Values.create(knxGatewayIp)), new MetaItem(KNXProtocol.META_KNX_LOCAL_IP, Values.create(knxLocalIp))));
        ServerAsset knxDevices = new ServerAsset("KNX Devices", THING, agent, masterRealmId);
        knxDevices = assetStorageService.merge(knxDevices);
    }
    if (velbus) {
        LOG.info("Enable Velbus demo protocol configuration, COM port: " + velbusComPort);
        agent.addAttributes(initProtocolConfiguration(new AssetAttribute("velbusConfig"), VelbusSerialProtocol.PROTOCOL_NAME).addMeta(new MetaItem(VelbusSerialProtocol.META_VELBUS_SERIAL_PORT, Values.create(velbusComPort))));
        ServerAsset velbusDevices = new ServerAsset("VELBUS Devices", THING, agent, masterRealmId);
        velbusDevices = assetStorageService.merge(velbusDevices);
    }
    if (upnp) {
        LOG.info("Enable UPnP demo protocol configuration");
        ServerAsset upnpDevices = new ServerAsset("UPnP Devices", THING, agent, masterRealmId);
        upnpDevices = assetStorageService.merge(upnpDevices);
        agent.addAttributes(initProtocolConfiguration(new AssetAttribute("upnpConfig"), UpnpProtocol.PROTOCOL_NAME).addMeta(// TODO Protocols should create these grouping assets automatically and import assets underneath for each protocol configuration
        new MetaItem(UpnpProtocol.GROUP_ASSET_ID, Values.create(upnpDevices.getId()))));
    }
    agent = assetStorageService.merge(agent);
}
Also used : Tenant(org.openremote.model.security.Tenant) MetaItem(org.openremote.model.attribute.MetaItem) ServerAsset(org.openremote.manager.asset.ServerAsset) AssetAttribute(org.openremote.model.asset.AssetAttribute)

Example 12 with AssetAttribute

use of org.openremote.model.asset.AssetAttribute in project openremote by openremote.

the class ManagerDemoSetup method onStart.

@Override
public void onStart() throws Exception {
    KeycloakDemoSetup keycloakDemoSetup = setupService.getTaskOfType(KeycloakDemoSetup.class);
    Tenant masterTenant = keycloakDemoSetup.masterTenant;
    Tenant customerATenant = keycloakDemoSetup.customerATenant;
    masterRealmId = masterTenant.getId();
    customerARealmId = customerATenant.getId();
    // ################################ Demo assets for 'master' realm ###################################
    ServerAsset smartOffice = new ServerAsset();
    smartOffice.setRealmId(masterTenant.getId());
    smartOffice.setName("Smart Office");
    smartOffice.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));
    smartOffice.setType(BUILDING);
    List<AssetAttribute> smartOfficeAttributes = Arrays.asList(new AssetAttribute("geoStreet", STRING, Values.create("Torenallee 20")).setMeta(new MetaItem(LABEL, Values.create("Street")), new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoStreet"))), new AssetAttribute("geoPostalCode", AttributeType.NUMBER, Values.create(5617)).setMeta(new MetaItem(LABEL, Values.create("Postal Code")), new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoPostalCode"))), new AssetAttribute("geoCity", STRING, Values.create("Eindhoven")).setMeta(new MetaItem(LABEL, Values.create("City")), new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCity"))), new AssetAttribute("geoCountry", STRING, Values.create("Netherlands")).setMeta(new MetaItem(LABEL, Values.create("Country")), new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCountry"))));
    smartOffice.setAttributes(smartOfficeAttributes);
    smartOffice = assetStorageService.merge(smartOffice);
    smartOfficeId = smartOffice.getId();
    ServerAsset groundFloor = new ServerAsset("Ground Floor", FLOOR, smartOffice);
    groundFloor.setLocation(smartOffice.getLocation());
    groundFloor = assetStorageService.merge(groundFloor);
    groundFloorId = groundFloor.getId();
    ServerAsset lobby = new ServerAsset("Lobby", ROOM, groundFloor);
    lobby.setLocation(groundFloor.getLocation());
    lobby = assetStorageService.merge(lobby);
    lobbyId = lobby.getId();
    ServerAsset agent = new ServerAsset("Demo Agent", AGENT, lobby);
    agent.setLocation(lobby.getLocation());
    agent.setAttributes(initProtocolConfiguration(new AssetAttribute(agentProtocolConfigName), SimulatorProtocol.PROTOCOL_NAME).addMeta(new MetaItem(SimulatorProtocol.CONFIG_MODE, Values.create(SimulatorProtocol.Mode.WRITE_THROUGH_DELAYED.toString())), new MetaItem(SimulatorProtocol.CONFIG_WRITE_DELAY_MILLISECONDS, Values.create(500))));
    agent = assetStorageService.merge(agent);
    agentId = agent.getId();
    ServerAsset thing = new ServerAsset("Demo Thing", THING, agent);
    thing.setLocation(agent.getLocation());
    thing.setAttributes(new AssetAttribute(thingLightToggleAttributeName, BOOLEAN, Values.create(true)).setMeta(new Meta(new MetaItem(LABEL, Values.create("Light 1 Toggle")), new MetaItem(DESCRIPTION, Values.create("Switch for living room light")), new MetaItem(STORE_DATA_POINTS, Values.create(true)), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(SwitchSimulatorElement.ELEMENT_NAME)))), // No initial value!
    new AssetAttribute("light1Dimmer", PERCENTAGE).setMeta(new Meta(new MetaItem(LABEL, Values.create("Light 1 Dimmer")), new MetaItem(DESCRIPTION, Values.create("Dimmer for living room light")), new MetaItem(RANGE_MIN, Values.create(0)), new MetaItem(RANGE_MAX, Values.create(100)), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME_RANGE)), new MetaItem(SimulatorProtocol.CONFIG_MODE, Values.create(SimulatorProtocol.Mode.WRITE_THROUGH_DELAYED.toString())))), new AssetAttribute("light1Color", COLOR_RGB, new ColorRGB(88, 123, 88).asArrayValue()).setMeta(new Meta(new MetaItem(LABEL, Values.create("Light 1 Color")), new MetaItem(DESCRIPTION, Values.create("Color of living room light")), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(ColorSimulatorElement.ELEMENT_NAME)))), new AssetAttribute("light1PowerConsumption", ENERGY_KWH, Values.create(12.345)).setMeta(new Meta(new MetaItem(LABEL, Values.create("Light 1 Usage")), new MetaItem(DESCRIPTION, Values.create("Total energy consumption of living room light")), new MetaItem(READ_ONLY, Values.create(true)), new MetaItem(FORMAT, Values.create("%3d kWh")), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)), new MetaItem(STORE_DATA_POINTS, Values.create(true)))));
    thing = assetStorageService.merge(thing);
    thingId = thing.getId();
    // Some sample datapoints
    final ServerAsset finalThing = assetStorageService.find(thingId, true);
    ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
    AssetAttribute light1PowerConsumptionAttribute = thing.getAttribute("light1PowerConsumption").orElseThrow(() -> new RuntimeException("Invalid test data"));
    persistenceService.doTransaction(em -> {
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(0.11), now.minusDays(80).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(1.22), now.minusDays(40).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(2.33), now.minusDays(20).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(3.44), now.minusDays(10).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(4.55), now.minusDays(8).toEpochSecond() * 1000);
        light1PowerConsumptionAttribute.setValue(Values.create(5.66), now.minusDays(6).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(6.77), now.minusDays(3).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(7.88), now.minusDays(1).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(8.99), now.minusHours(10).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(9.11), now.minusHours(5).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(10.22), now.minusHours(2).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(11.33), now.minusHours(1).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(11.44), now.minusMinutes(30).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(12.00), now.minusMinutes(5).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(12.11), now.minusSeconds(5).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
        light1PowerConsumptionAttribute.setValue(Values.create(12.22), now.minusSeconds(1).toEpochSecond() * 1000);
        assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);
    });
    // ################################ Demo assets for 'customerA' realm ###################################
    ServerAsset smartHome = new ServerAsset();
    smartHome.setRealmId(customerATenant.getId());
    smartHome.setName("Smart Home");
    smartHome.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));
    smartHome.setType(BUILDING);
    smartHome.setAttributes(new AssetAttribute("geoStreet", STRING, Values.create("Wilhelminaplein 21C")).setMeta(new MetaItem(LABEL, Values.create("Street")), new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoStreet"))), new AssetAttribute("geoPostalCode", AttributeType.NUMBER, Values.create(5611)).setMeta(new MetaItem(LABEL, Values.create("Postal Code")), new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoPostalCode"))), new AssetAttribute("geoCity", STRING, Values.create("Eindhoven")).setMeta(new MetaItem(LABEL, Values.create("City")), new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCity"))), new AssetAttribute("geoCountry", STRING, Values.create("Netherlands")).setMeta(new MetaItem(LABEL, Values.create("Country")), new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCountry"))));
    smartHome = assetStorageService.merge(smartHome);
    smartHomeId = smartHome.getId();
    // The "Apartment 1" is the demo apartment with complex scenes
    ServerAsset apartment1 = createDemoApartment(smartHome, "Apartment 1");
    apartment1 = assetStorageService.merge(apartment1);
    apartment1Id = apartment1.getId();
    ServerAsset apartment1ServiceAgent = new ServerAsset("Service Agent (Simulator)", AGENT, apartment1);
    apartment1ServiceAgent.setAttributes(initProtocolConfiguration(new AssetAttribute("apartmentSimulator"), SimulatorProtocol.PROTOCOL_NAME).addMeta(new MetaItem(SimulatorProtocol.CONFIG_MODE, Values.create(SimulatorProtocol.Mode.WRITE_THROUGH_IMMEDIATE.toString()))));
    apartment1ServiceAgent = assetStorageService.merge(apartment1ServiceAgent);
    apartment1ServiceAgentId = apartment1ServiceAgent.getId();
    /* ############################ ROOMS ############################## */
    ServerAsset apartment1Livingroom = createDemoApartmentRoom(apartment1, "Living Room");
    addDemoApartmentRoomMotionSensor(apartment1Livingroom, true, () -> new MetaItem[] { new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) });
    addDemoApartmentRoomCO2Sensor(apartment1Livingroom, true, () -> new MetaItem[] { new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) });
    addDemoApartmentRoomHumiditySensor(apartment1Livingroom, true, () -> new MetaItem[] { new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) });
    addDemoApartmentRoomThermometer(apartment1Livingroom, true, () -> new MetaItem[] { new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) });
    addDemoApartmentTemperatureControl(apartment1Livingroom, true, () -> new MetaItem[] { new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) });
    apartment1Livingroom = assetStorageService.merge(apartment1Livingroom);
    apartment1LivingroomId = apartment1Livingroom.getId();
    ServerAsset apartment1Kitchen = createDemoApartmentRoom(apartment1, "Kitchen");
    addDemoApartmentRoomMotionSensor(apartment1Kitchen, true, () -> new MetaItem[] { new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) });
    for (String switchName : new String[] { "A", "B", "C" }) {
        addDemoApartmentSmartSwitch(apartment1Kitchen, switchName, true, attributeIndex -> {
            switch(attributeIndex) {
                case 2:
                    return new MetaItem[] { new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) };
                case 3:
                    return new MetaItem[] { new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) };
                case 4:
                    return new MetaItem[] { new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) };
            }
            return null;
        });
    }
    apartment1Kitchen = assetStorageService.merge(apartment1Kitchen);
    apartment1KitchenId = apartment1Kitchen.getId();
    ServerAsset apartment1Hallway = createDemoApartmentRoom(apartment1, "Hallway");
    addDemoApartmentRoomMotionSensor(apartment1Hallway, true, () -> new MetaItem[] { new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) });
    apartment1Hallway = assetStorageService.merge(apartment1Hallway);
    apartment1HallwayId = apartment1Hallway.getId();
    addDemoApartmentVentilation(apartment1, true, () -> new MetaItem[] { new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()), new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)) });
    apartment1 = assetStorageService.merge(apartment1);
    if (importDemoScenes) {
        Scene[] scenes = new Scene[] { new Scene("homeScene", "Home scene", "HOME", "0 0 7 ? *", false, 21d), new Scene("awayScene", "Away scene", "AWAY", "0 30 8 ? *", true, 15d), new Scene("eveningScene", "Evening scene", "EVENING", "0 30 17 ? *", false, 22d), new Scene("nightScene", "Night scene", "NIGHT", "0 0 22 ? *", true, 19d) };
        ServerAsset demoApartmentSceneAgent = createDemoApartmentSceneAgent(apartment1, scenes, apartment1Livingroom, apartment1Kitchen, apartment1Hallway);
        demoApartmentSceneAgent = assetStorageService.merge(demoApartmentSceneAgent);
        linkDemoApartmentWithSceneAgent(apartment1, demoApartmentSceneAgent, scenes);
        apartment1 = assetStorageService.merge(apartment1);
    }
    ServerAsset apartment2 = new ServerAsset("Apartment 2", RESIDENCE, smartHome);
    apartment2.setLocation(smartHome.getLocation());
    apartment2.setAttributes(new AssetAttribute("allLightsOffSwitch", AttributeType.BOOLEAN, Values.create(true)).setMeta(new MetaItem(LABEL, Values.create("All Lights Off Switch")), new MetaItem(DESCRIPTION, Values.create("When triggered, turns all lights in the apartment off")), new MetaItem(RULE_EVENT, Values.create(true)), new MetaItem(RULE_EVENT_EXPIRES, Values.create("3s"))));
    apartment2 = assetStorageService.merge(apartment2);
    apartment2Id = apartment2.getId();
    ServerAsset apartment2Livingroom = new ServerAsset("Living Room", ROOM, apartment2);
    apartment2Livingroom.setLocation(apartment2.getLocation());
    apartment2Livingroom.setAttributes(new AssetAttribute("motionSensor", AttributeType.BOOLEAN, Values.create(false)).setMeta(new MetaItem(LABEL, Values.create("Motion Sensor")), new MetaItem(DESCRIPTION, Values.create("PIR sensor that sends 'true' when motion is sensed")), new MetaItem(RULE_STATE, Values.create(true)), new MetaItem(RULE_EVENT, Values.create(true))), new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Values.create(false)).setMeta(new MetaItem(LABEL, Values.create("Presence Detected")), new MetaItem(DESCRIPTION, Values.create("Someone is currently present in the room")), new MetaItem(RULE_STATE, Values.create(true))), new AssetAttribute("firstPresenceDetected", AttributeType.TIMESTAMP_MILLIS).setMeta(new MetaItem(LABEL, Values.create("First Presence Timestamp")), new MetaItem(DESCRIPTION, Values.create("Timestamp of the first detected presence")), new MetaItem(RULE_STATE, Values.create(true))), new AssetAttribute("lastPresenceDetected", AttributeType.TIMESTAMP_MILLIS).setMeta(new MetaItem(LABEL, Values.create("Last Presence Timestamp")), new MetaItem(DESCRIPTION, Values.create("Timestamp of last detected presence")), new MetaItem(RULE_STATE, Values.create(true))), new AssetAttribute("co2Level", AttributeType.CO2_PPM, Values.create(350)).setMeta(new MetaItem(LABEL, Values.create("CO2 Level")), new MetaItem(RULE_STATE, Values.create(true))), new AssetAttribute("lightSwitch", AttributeType.BOOLEAN, Values.create(true)).setMeta(new MetaItem(LABEL, Values.create("Light Switch")), new MetaItem(RULE_STATE, Values.create(true))), new AssetAttribute("windowOpen", AttributeType.BOOLEAN, Values.create(false)).setMeta(new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true))));
    apartment2Livingroom = assetStorageService.merge(apartment2Livingroom);
    apartment2LivingroomId = apartment2Livingroom.getId();
    ServerAsset apartment2Bathroom = new ServerAsset("Bathroom", ROOM, apartment2);
    apartment2Bathroom.setLocation(apartment2.getLocation());
    apartment2Bathroom.setAttributes(new AssetAttribute("motionSensor", AttributeType.BOOLEAN, Values.create(false)).setMeta(new MetaItem(LABEL, Values.create("Motion Sensor")), new MetaItem(DESCRIPTION, Values.create("PIR sensor that sends 'true' when motion is sensed")), new MetaItem(RULE_STATE, Values.create(true)), new MetaItem(RULE_EVENT, Values.create(true))), new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Values.create(false)).setMeta(new MetaItem(LABEL, Values.create("Presence Detected")), new MetaItem(DESCRIPTION, Values.create("Someone is currently present in the room")), new MetaItem(RULE_STATE, Values.create(true))), new AssetAttribute("firstPresenceDetected", AttributeType.TIMESTAMP_MILLIS).setMeta(new MetaItem(LABEL, Values.create("First Presence Timestamp")), new MetaItem(DESCRIPTION, Values.create("Timestamp of the first detected presence")), new MetaItem(RULE_STATE, Values.create(true))), new AssetAttribute("lastPresenceDetected", AttributeType.TIMESTAMP_MILLIS).setMeta(new MetaItem(LABEL, Values.create("Last Presence Timestamp")), new MetaItem(DESCRIPTION, Values.create("Timestamp of last detected presence")), new MetaItem(RULE_STATE, Values.create(true))), new AssetAttribute("lightSwitch", AttributeType.BOOLEAN, Values.create(true)).setMeta(new MetaItem(LABEL, Values.create("Light Switch")), new MetaItem(RULE_STATE, Values.create(true))));
    apartment2Bathroom = assetStorageService.merge(apartment2Bathroom);
    apartment2BathroomId = apartment2Bathroom.getId();
    ServerAsset apartment3 = new ServerAsset("Apartment 3", RESIDENCE, smartHome);
    apartment3.setLocation(smartHome.getLocation());
    apartment3 = assetStorageService.merge(apartment3);
    apartment3Id = apartment3.getId();
    ServerAsset apartment3Livingroom = new ServerAsset("Living Room", ROOM, apartment3);
    apartment3Livingroom.setLocation(apartment3.getLocation());
    apartment3Livingroom.addAttributes(new AssetAttribute("lightSwitch", AttributeType.BOOLEAN));
    apartment3Livingroom = assetStorageService.merge(apartment3Livingroom);
    apartment3LivingroomId = apartment3Livingroom.getId();
    // ################################ Link demo users and assets ###################################
    assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1Id));
    assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1LivingroomId));
    assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1KitchenId));
    assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1HallwayId));
    assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment2Id));
}
Also used : AssetMeta(org.openremote.model.asset.AssetMeta) UserAsset(org.openremote.model.asset.UserAsset) ServerAsset(org.openremote.manager.asset.ServerAsset) Tenant(org.openremote.model.security.Tenant) Coordinate(com.vividsolutions.jts.geom.Coordinate) ZonedDateTime(java.time.ZonedDateTime) AssetAttribute(org.openremote.model.asset.AssetAttribute)

Example 13 with AssetAttribute

use of org.openremote.model.asset.AssetAttribute in project openremote by openremote.

the class TimerProtocol method processLinkedAttributeWrite.

@Override
protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {
    AssetAttribute attribute = getLinkedAttribute(event.getAttributeRef());
    TimerValue timerValue = TimerConfiguration.getValue(attribute).orElse(null);
    if (timerValue == null) {
        LOG.warning("Attribute doesn't have a valid timer value so ignoring write request: " + attribute.getReferenceOrThrow());
        return;
    }
    // Don't remove or alter any running timer just push update back through the system and wait for link/unlink
    // protocol configuration method call
    Optional<String> writeValue = event.getValue().flatMap(Values::getString).flatMap(TextUtil::asNonNullAndNonEmpty);
    switch(timerValue) {
        case ENABLED:
            // check event value is a boolean
            boolean enabled = Values.getBoolean(event.getValue().orElse(null)).orElseThrow(() -> new IllegalStateException("Writing to protocol configuration CONNECTED property requires a boolean value"));
            if (enabled == protocolConfiguration.isEnabled()) {
                LOG.finer("Protocol configuration enabled status is already: " + enabled);
            } else {
                LOG.fine("Updating protocol configuration enabled status");
                updateLinkedProtocolConfiguration(protocolConfiguration, protocolConfig -> protocolConfig.setDisabled(!enabled));
            }
            break;
        case CRON_EXPRESSION:
            // but that is handled gracefully
            if (!writeValue.isPresent()) {
                LOG.warning("Send to actuator value for time trigger must be a non empty string");
                return;
            }
            updateTimerValue(new AttributeState(protocolConfiguration.getReferenceOrThrow(), Values.create(writeValue.get().trim())));
            break;
        case TIME:
            if (!writeValue.isPresent()) {
                LOG.warning("Send to actuator value for time trigger must be a non empty string");
                return;
            }
            CronExpressionParser parser = cronExpressionMap.get(protocolConfiguration.getReferenceOrThrow());
            if (parser == null) {
                LOG.info("Ignoring trigger update because current cron expression is invalid");
                return;
            }
            String[] writeTimeValues = writeValue.get().trim().split(":");
            Integer hours;
            Integer minutes;
            Integer seconds;
            if (writeTimeValues.length != 3 || (hours = CronExpressionParser.parseNumberExpression(writeTimeValues[0])) == null || (minutes = CronExpressionParser.parseNumberExpression(writeTimeValues[1])) == null || (seconds = CronExpressionParser.parseNumberExpression(writeTimeValues[2])) == null) {
                LOG.info("Expected value to be in format HH:MM:SS, actual: " + writeValue);
                return;
            }
            parser.setTime(hours, minutes, seconds);
            updateTimerValue(new AttributeState(protocolConfiguration.getReferenceOrThrow(), Values.create(parser.buildCronExpression())));
            break;
        default:
            throw new NotSupportedException("Unsupported timer value: " + timerValue);
    }
}
Also used : TextUtil(org.openremote.model.util.TextUtil) AssetAttribute(org.openremote.model.asset.AssetAttribute) NotSupportedException(javax.ws.rs.NotSupportedException)

Example 14 with AssetAttribute

use of org.openremote.model.asset.AssetAttribute in project openremote by openremote.

the class UpnpProtocol method createAsset.

protected Asset createAsset(String parentId, Device device) {
    Asset asset = new Asset(device.getDisplayString(), AssetType.THING);
    asset.setParentId(parentId);
    asset.setId(getAssetId(device));
    long currentTime = timerService.getCurrentTimeMillis();
    Optional.ofNullable(device.getType().getDisplayString()).ifPresent(v -> asset.addAttributes(new AssetAttribute("type", STRING, Values.create(v), currentTime).addMeta(new MetaItem(LABEL, Values.create("Device Type")))));
    Optional.ofNullable(device.getDetails().getManufacturerDetails().getManufacturer()).ifPresent(v -> asset.addAttributes(new AssetAttribute("manufacturer", STRING, Values.create(v), currentTime).addMeta(new MetaItem(LABEL, Values.create("Manufacturer")))));
    Optional.ofNullable(device.getDetails().getFriendlyName()).ifPresent(v -> asset.addAttributes(new AssetAttribute("friendlyName", STRING, Values.create(v), currentTime).addMeta(new MetaItem(LABEL, Values.create("Friendly Name")))));
    Optional.ofNullable(device.getDetails().getModelDetails().getModelNumber()).ifPresent(v -> asset.addAttributes(new AssetAttribute("modelNumber", STRING, Values.create(v), currentTime).addMeta(new MetaItem(LABEL, Values.create("Model Number")))));
    Optional.ofNullable(device.getDetails().getModelDetails().getModelName()).ifPresent(v -> asset.addAttributes(new AssetAttribute("modelName", STRING, Values.create(v), currentTime).addMeta(new MetaItem(LABEL, Values.create("Model Name")))));
    Optional.ofNullable(device.getDetails().getModelDetails().getModelDescription()).ifPresent(v -> asset.addAttributes(new AssetAttribute("modelDescription", STRING, Values.create(v), currentTime).addMeta(new MetaItem(LABEL, Values.create("Model Description")))));
    Optional.ofNullable(device.getDetails().getSerialNumber()).ifPresent(v -> asset.addAttributes(new AssetAttribute("serialNumber", STRING, Values.create(v), currentTime).addMeta(new MetaItem(LABEL, Values.create("Serial Number")))));
    return asset;
}
Also used : MetaItem(org.openremote.model.attribute.MetaItem) AssetAttribute(org.openremote.model.asset.AssetAttribute) Asset(org.openremote.model.asset.Asset)

Example 15 with AssetAttribute

use of org.openremote.model.asset.AssetAttribute in project openremote by openremote.

the class AbstractVelbusProtocol method discoverLinkedAssetAttributes.

@Override
public Asset[] discoverLinkedAssetAttributes(AssetAttribute protocolConfiguration, FileInfo fileInfo) throws IllegalStateException {
    Document xmlDoc;
    try {
        String xmlStr = fileInfo.isBinary() ? new String(CodecUtil.decodeBase64(fileInfo.getContents()), "UTF8") : fileInfo.getContents();
        LOG.info("Parsing VELBUS project file: " + fileInfo.getName());
        xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xmlStr)));
    } catch (Exception e) {
        throw new IllegalStateException("Failed to convert file into XML", e);
    }
    xmlDoc.getDocumentElement().normalize();
    NodeList modules = xmlDoc.getElementsByTagName("Module");
    LOG.info("Found " + modules.getLength() + " module(s)");
    List<Asset> devices = new ArrayList<>(modules.getLength());
    MetaItem agentLink = AgentLink.asAgentLinkMetaItem(protocolConfiguration.getReferenceOrThrow());
    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(",");
        Integer 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;
        Asset device = new Asset(name, AssetType.THING);
        device.setAttributes(new AssetAttribute("build", AttributeType.STRING, Values.create(build)).setMeta(new MetaItem(AssetMeta.LABEL, Values.create("Build")), new MetaItem(AssetMeta.READ_ONLY, Values.create(true))), new AssetAttribute("serialNumber", AttributeType.STRING, Values.create(serial)).setMeta(new MetaItem(AssetMeta.LABEL, Values.create("Serial No")), new MetaItem(AssetMeta.READ_ONLY, Values.create(true))));
        getLinkedAttributeDescriptors(deviceType.get(), baseAddress).forEach(descriptor -> {
            AssetAttribute attribute = new AssetAttribute(descriptor.getName(), descriptor.getAttributeType()).setMeta(agentLink, new MetaItem(AssetMeta.LABEL, Values.create(descriptor.getDisplayName()))).addMeta(descriptor.getMetaItems());
            if (descriptor.isReadOnly()) {
                attribute.addMeta(new MetaItem(AssetMeta.READ_ONLY, Values.create(true)));
            } else if (descriptor.isExecutable()) {
                attribute.addMeta(new MetaItem(AssetMeta.EXECUTABLE, Values.create(true)));
            }
            device.addAttributes(attribute);
        });
        devices.add(device);
    }
    return devices.toArray(new Asset[devices.size()]);
}
Also used : 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) StringReader(java.io.StringReader) AssetAttribute(org.openremote.model.asset.AssetAttribute) Asset(org.openremote.model.asset.Asset)

Aggregations

AssetAttribute (org.openremote.model.asset.AssetAttribute)26 Logger (java.util.logging.Logger)7 Level (java.util.logging.Level)6 Asset (org.openremote.model.asset.Asset)6 AssetMeta (org.openremote.model.asset.AssetMeta)6 Values (org.openremote.model.value.Values)6 List (java.util.List)5 Optional (java.util.Optional)5 Consumer (java.util.function.Consumer)5 Container (org.openremote.container.Container)5 ProtocolConfiguration (org.openremote.model.asset.agent.ProtocolConfiguration)5 Pair (org.openremote.model.util.Pair)5 java.util (java.util)4 Protocol (org.openremote.agent.protocol.Protocol)4 GlobalLock.withLock (org.openremote.container.concurrent.GlobalLock.withLock)4 TextUtil (org.openremote.model.util.TextUtil)4 TimeUnit (java.util.concurrent.TimeUnit)3 HttpMethod (javax.ws.rs.HttpMethod)3 AbstractProtocol (org.openremote.agent.protocol.AbstractProtocol)3 ServerAsset (org.openremote.manager.asset.ServerAsset)3