Пример #1
0
        def build_context_entity_from_device(device: Device) -> ContextEntity:
            from filip.models.base import DataType
            entity = ContextEntity(id=device.entity_name,
                                   type=device.entity_type)

            for command in device.commands:
                entity.add_attributes([
                    # Command attribute will be registered by the device_update
                    NamedContextAttribute(name=f"{command.name}_info",
                                          type=DataType.COMMAND_RESULT),
                    NamedContextAttribute(name=f"{command.name}_status",
                                          type=DataType.COMMAND_STATUS)
                ])
            for attribute in device.attributes:
                entity.add_attributes([
                    NamedContextAttribute(name=attribute.name,
                                          type=DataType.STRUCTUREDVALUE,
                                          metadata=attribute.metadata)
                ])
            for static_attribute in device.static_attributes:
                entity.add_attributes([
                    NamedContextAttribute(name=static_attribute.name,
                                          type=static_attribute.type,
                                          value=static_attribute.value,
                                          metadata=static_attribute.metadata)
                ])
            return entity
Пример #2
0
 def create_entity(self):
     """Creates entitiy of PID controller in orion context broker"""
     try:
         self.ORION_CB.get_entity(entity_id=self.params['controller_name'],
                                  entity_type=self.params['type'])
         print('Entity name already assigned')
     except requests.exceptions.HTTPError as err:
         msg = err.args[0]
         if "NOT FOUND" not in msg.upper():
             raise  # throw other errors except "entity not found"
         print('[INFO]: Create new PID entity')
         pid_entity = ContextEntity(id=f"{self.params['controller_name']}",
                                    type=self.params['type'])
         cb_attrs = []
         for attr in ['Kp', 'Ki', 'Kd', 'lim_low', 'lim_upper', 'setpoint']:
             cb_attrs.append(
                 NamedContextAttribute(name=attr,
                                       type="Number",
                                       value=self.params[attr]))
         pid_entity.add_attributes(attrs=cb_attrs)
         self.ORION_CB.post_entity(entity=pid_entity, update=True)
Пример #3
0
    # ToDo: Get context entities from the Context Broker
    #  (exclude the IoT device ones)
    building = cbc.get_entity(entity_id="urn:ngsi-ld:building:001",
                              entity_type="Building")
    thermal_zone = cbc.get_entity(entity_id="ThermalZone:001",
                                  entity_type="ThermalZone")

    # ToDo: Semantically connect the weather station and the building. By
    #  adding a `hasWeatherStation` attribute of type `Relationship`. For the
    #  connection from the weather station to the building add a static
    #  attribute to the weather station

    # create the context attribute for the building and add it to the
    # building entity
    has_weather_station = NamedContextAttribute(
        name="hasWeatherStation",
        type="Relationship",
        value=weather_station.entity_name)
    building.add_attributes(attrs=[has_weather_station])

    # create a static attribute that connects the weather station to the
    # building
    cbc.update_entity(entity=building)

    ref_building = StaticDeviceAttribute(name="refBuilding",
                                         type="Relationship",
                                         value=building.id)
    weather_station.add_attribute(ref_building)
    iotac.update_device(device=weather_station)

    # ToDo: Semantically connect the zone temperature sensor and the thermal
    #  zone by adding a `hasTemperatureSensor` attribute of type
Пример #4
0
        "temperature": {
            "value": 11,
            "type": "Float"
        },
        "pressure": {
            "value": 111,
            "type": "Integer"
        }
    }
    room1_entity = ContextEntity(**room1)

    # ### 2.1.2 Using the constructor and interfaces
    #
    room2_entity = ContextEntity(id="Room2", type="Room")
    temp_attr = NamedContextAttribute(name="temperature",
                                      value=22,
                                      type=DataType.FLOAT)
    pressure_attr = NamedContextAttribute(name="pressure",
                                          value=222,
                                          type="Integer")
    room2_entity.add_attributes([temp_attr, pressure_attr])

    # ## 2.2 Post Entities
    #
    print(cb_client.get_entity_list())
    cb_client.post_entity(entity=room1_entity)
    cb_client.post_entity(entity=room2_entity)

    # # 3 Access entities in Fiware
    #
    # Get all entities from context broker
Пример #5
0
WRITE_ENTITIES_FILEPATH = Path("")

# ## Main script
if __name__ == '__main__':
    # create a fiware header object
    fiware_header = FiwareHeader(service=SERVICE, service_path=SERVICE_PATH)
    # clear the state of your service and scope
    clear_context_broker(url=CB_URL, fiware_header=fiware_header)

    # Create a context entity for a `building` following the smart data models
    # specifications
    building = ContextEntity(id="urn:ngsi-ld:building:001", type="Building")

    # create the property `category` to your building
    category = NamedContextAttribute(name="category",
                                     type="Array",
                                     value=["office"])

    # ToDo: create a property `address` for your building. Follow the full yaml
    #  description in the specifications. It reuses the specification from
    #  here: https://schema.org/PostalAddress
    address = NamedContextAttribute(name="address",
                                    type="PostalAddress",
                                    value={...})

    # ToDo: create a `description` property for your building
    building_description = NamedContextAttribute(...)

    # add all properties to your building using the
    # `add_attribute` function of your building object
    building.add_attributes(attrs=[building_description, category, address])
WRITE_ENTITIES_FILEPATH = Path("e3_context_entities_solution_entities.json")

# ## Main script
if __name__ == '__main__':
    # create a fiware header object
    fiware_header = FiwareHeader(service=SERVICE, service_path=SERVICE_PATH)
    # clear the state of your service and scope
    clear_context_broker(url=CB_URL, fiware_header=fiware_header)

    # Create a context entity for a `building` following the smart data models
    # specifications
    building = ContextEntity(id="urn:ngsi-ld:building:001", type="Building")

    # create the property `category` to your building
    category = NamedContextAttribute(name="category",
                                     type="Array",
                                     value=["office"])

    # ToDo: create a property `address` for your building. Follow the full yaml
    #  description in the specifications. It reuses the specification from
    #  here: https://schema.org/PostalAddress
    address = NamedContextAttribute(name="address",
                                    type="PostalAddress",
                                    value={
                                        "addressCountry": "DE",
                                        "addressLocality": "Any City",
                                        "postalCode": "12345",
                                        "streetAddress": "Any Street 5"
                                    })

    # ToDo: create a `description` property for your building
Пример #7
0
    def test_patch_entity(self) -> None:
        """
        Test the methode: patch_entity
        Returns:
           None
        """

        # setup test-entity
        entity = ContextEntity(id="test_id1", type="test_type1")
        attr1 = NamedContextAttribute(name="attr1", value="1")
        attr1.metadata["m1"] = \
            NamedMetadata(name="meta1", type="metatype", value="2")
        attr2 = NamedContextAttribute(name="attr2", value="2")
        attr1.metadata["m2"] = \
            NamedMetadata(name="meta2", type="metatype", value="3")
        entity.add_attributes([attr1, attr2])

        # sub-Test1: Post new
        self.client.patch_entity(entity=entity)
        self.assertEqual(entity,
                         self.client.get_entity(entity_id=entity.id))
        self.tearDown()

        # sub-Test2: ID/type of old_entity changed
        self.client.post_entity(entity=entity)
        test_entity = ContextEntity(id="newID", type="newType")
        test_entity.add_attributes([attr1, attr2])
        self.client.patch_entity(test_entity, old_entity=entity)
        self.assertEqual(test_entity,
                         self.client.get_entity(entity_id=test_entity.id))
        self.assertRaises(RequestException, self.client.get_entity,
                          entity_id=entity.id)
        self.tearDown()

        # sub-Test3: a non valid old_entity is provided, entity exists
        self.client.post_entity(entity=entity)
        old_entity = ContextEntity(id="newID", type="newType")

        self.client.patch_entity(entity, old_entity=old_entity)
        self.assertEqual(entity, self.client.get_entity(entity_id=entity.id))
        self.tearDown()

        # sub-Test4: no old_entity provided, entity is new
        old_entity = ContextEntity(id="newID", type="newType")
        self.client.patch_entity(entity, old_entity=old_entity)
        self.assertEqual(entity, self.client.get_entity(entity_id=entity.id))
        self.tearDown()

        # sub-Test5: no old_entity provided, entity is new
        old_entity = ContextEntity(id="newID", type="newType")
        self.client.patch_entity(entity, old_entity=old_entity)
        self.assertEqual(entity, self.client.get_entity(entity_id=entity.id))
        self.tearDown()

        # sub-Test6: New attr, attr del, and attr changed. No Old_entity given
        self.client.post_entity(entity=entity)
        test_entity = ContextEntity(id="test_id1", type="test_type1")
        attr1_changed = NamedContextAttribute(name="attr1", value="2")
        attr1_changed.metadata["m4"] = \
            NamedMetadata(name="meta3", type="metatype5", value="4")
        attr3 = NamedContextAttribute(name="attr3", value="3")
        test_entity.add_attributes([attr1_changed, attr3])
        self.client.patch_entity(test_entity)

        self.assertEqual(test_entity,
                         self.client.get_entity(entity_id=entity.id))
        self.tearDown()

        # sub-Test7: Attr changes, concurrent changes in Fiware,
        #            old_entity given

        self.client.post_entity(entity=entity)

        concurrent_entity = ContextEntity(id="test_id1", type="test_type1")
        attr1_changed = copy.deepcopy(attr1)
        attr1_changed.metadata["m1"].value = "3"
        attr1_changed.value = "4"
        concurrent_entity.add_attributes([attr1_changed, attr2])
        self.client.patch_entity(concurrent_entity)

        user_entity = copy.deepcopy(entity)
        attr3 = NamedContextAttribute(name="attr3", value="3")
        user_entity.add_attributes([attr3])
        self.client.patch_entity(user_entity, old_entity=entity)

        result_entity = concurrent_entity
        result_entity.add_attributes([attr2, attr3])

        self.assertEqual(result_entity,
                         self.client.get_entity(entity_id=entity.id))
        self.tearDown()
Пример #8
0
    def test_attribute_operations(self):
        """
        Test attribute operations of context broker client
        """
        with ContextBrokerClient(
                url=settings.CB_URL,
                fiware_header=self.fiware_header) as client:
            entity = self.entity
            attr_txt = NamedContextAttribute(name='attr_txt',
                                             type='Text',
                                             value="Test")
            attr_bool = NamedContextAttribute(name='attr_bool',
                                              type='Boolean',
                                              value=True)
            attr_float = NamedContextAttribute(name='attr_float',
                                               type='Number',
                                               value=round(random.random(), 5))
            attr_list = NamedContextAttribute(name='attr_list',
                                              type='StructuredValue',
                                              value=[1, 2, 3])
            attr_dict = NamedContextAttribute(name='attr_dict',
                                              type='StructuredValue',
                                              value={'key': 'value'})
            entity.add_attributes([attr_txt,
                                   attr_bool,
                                   attr_float,
                                   attr_list,
                                   attr_dict])

            self.assertIsNotNone(client.post_entity(entity=entity,
                                                    update=True))
            res_entity = client.get_entity(entity_id=entity.id)

            for attr in entity.get_properties():
                self.assertIn(attr, res_entity.get_properties())
                res_attr = client.get_attribute(entity_id=entity.id,
                                                attr_name=attr.name)

                self.assertEqual(type(res_attr.value), type(attr.value))
                self.assertEqual(res_attr.value, attr.value)
                value = client.get_attribute_value(entity_id=entity.id,
                                                   attr_name=attr.name)
                # unfortunately FIWARE returns an int for 20.0 although float
                # is expected
                if isinstance(value, int) and not isinstance(value, bool):
                    value = float(value)
                self.assertEqual(type(value), type(attr.value))
                self.assertEqual(value, attr.value)

            for attr_name, attr in entity.get_properties(
                    response_format='dict').items():

                client.update_entity_attribute(entity_id=entity.id,
                                               attr_name=attr_name,
                                               attr=attr)
                value = client.get_attribute_value(entity_id=entity.id,
                                                   attr_name=attr_name)
                # unfortunately FIWARE returns an int for 20.0 although float
                # is expected
                if isinstance(value, int) and not isinstance(value, bool):
                    value = float(value)
                self.assertEqual(type(value), type(attr.value))
                self.assertEqual(value, attr.value)

            new_value = 1337.0
            client.update_attribute_value(entity_id=entity.id,
                                          attr_name='temperature',
                                          value=new_value)
            attr_value = client.get_attribute_value(entity_id=entity.id,
                                                    attr_name='temperature')
            self.assertEqual(attr_value, new_value)
Пример #9
0
    # ToDo: Get context entities from the Context Broker
    #  (exclude the IoT device ones)
    building = cbc.get_entity(entity_id="urn:ngsi-ld:building:001",
                              entity_type="Building")
    thermal_zone = cbc.get_entity(entity_id="ThermalZone:001",
                                  entity_type="ThermalZone")

    # ToDo: Semantically connect the weather station and the building. By
    #  adding a `hasWeatherStation` attribute of type `Relationship`. For the
    #  connection from the weather station to the building add a static
    #  attribute to the weather station.

    # create the context attribute for the building and add it to the
    # building entity
    has_weather_station = NamedContextAttribute(
        name="hasWeatherStation",
        type="Relationship",
        value=weather_station.entity_name)
    building.add_attributes(attrs=[has_weather_station])

    # create a static attribute that connects the weather station to the
    # building
    cbc.update_entity(entity=building)

    ref_building = StaticDeviceAttribute(name="refBuilding",
                                         type="Relationship",
                                         value=building.id)
    weather_station.add_attribute(ref_building)
    iotac.update_device(device=weather_station)

    # ToDo: Semantically connect the zone temperature sensor and the thermal
    #  zone by adding a `hasTemperatureSensor` attribute of type