def clear_context_broker(url: str, fiware_header: FiwareHeader): """ Function deletes all entities, registrations and subscriptions for a given fiware header Note: Always clear the devices first because the IoT-Agent will otherwise through errors if it cannot find its registration anymore. Args: url: Url of the context broker service fiware_header: header of the tenant Returns: None """ # create client client = ContextBrokerClient(url=url, fiware_header=fiware_header) # clean entities client.delete_entities(entities=client.get_entity_list()) # clear subscriptions for sub in client.get_subscription_list(): client.delete_subscription(subscription_id=sub.id) assert len(client.get_subscription_list()) == 0 # clear registrations for reg in client.get_registration_list(): client.delete_registration(registration_id=reg.id) assert len(client.get_registration_list()) == 0
def test_deletions(self): """ Test the deletion of a context entity/device if the state is always correctly cleared """ self.tearDown() device_id = 'device_id' entity_id = 'entity_id' device = Device(device_id=device_id, entity_name=entity_id, entity_type='Thing2', protocol='IoTA-JSON', transport='HTTP', apikey='filip-iot-test-device') cb_client = ContextBrokerClient(url=settings.CB_URL, fiware_header=self.fiware_header) # Test 1: Only delete device # delete without optional parameter -> entity needs to continue existing self.client.post_device(device=device) self.client.delete_device(device_id=device_id, cb_url=settings.CB_URL) self.assertTrue( len(cb_client.get_entity_list(entity_ids=[entity_id])) == 1) cb_client.delete_entity(entity_id=entity_id, entity_type='Thing2') # Test 2:Delete device and corresponding entity # delete with optional parameter -> entity needs to be deleted self.client.post_device(device=device) self.client.delete_device(device_id=device_id, cb_url=settings.CB_URL, delete_entity=True) self.assertTrue( len(cb_client.get_entity_list(entity_ids=[entity_id])) == 0) # Test 3:Delete device and corresponding entity, # that is linked to multiple devices # delete with optional parameter -> entity needs to be deleted self.client.post_device(device=device) device2 = copy.deepcopy(device) device2.device_id = "device_id2" self.client.post_device(device=device2) self.assertRaises(Exception, self.client.delete_device, device_id=device_id, delete_entity=True) self.assertTrue( len(cb_client.get_entity_list(entity_ids=[entity_id])) == 1) self.client.delete_device(device_id=device2.device_id) # Test 4: Only delete entity # delete without optional parameter -> device needs to continue existing self.client.post_device(device=device) cb_client.delete_entity(entity_id=entity_id, entity_type='Thing2') self.client.get_device(device_id=device_id) self.client.delete_device(device_id=device_id) # Test 5: Delete entity, and all devices # # delete with optional parameter -> all devices need to be deleted self.client.post_device(device=device) device2 = copy.deepcopy(device) device2.device_id = "device_id2" self.client.post_device(device=device2) cb_client.delete_entity(entity_id=entity_id, delete_devices=True, entity_type='Thing2', iota_url=settings.IOTA_JSON_URL) self.assertEqual(len(self.client.get_device_list()), 0)
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 logger.info(cb_client.get_entity_list()) # Get entities by id logger.info(cb_client.get_entity_list(entity_ids=["Room1"])) # Get entities by type logger.info(cb_client.get_entity_list(entity_types=["Room"])) # Get entities by id pattern
ref_zone = NamedContextAttribute(name="hasZone", type="Relationship", value=thermal_zone.id) cbc.update_or_append_entity_attributes(entity_id=building.id, entity_type=building.type, attrs=[ref_zone]) building = cbc.get_entity(entity_id=building.id, entity_type=building.type) # ToDo: create a filter request that retrieves all entities from the # server`that have `refBuilding` attribute that references your building # by using the FIWARE's simple query language. # `filip.utils.simple_ql` module helps you to validate your query string # 1. prepare the query string using the `filip.utils.simple_ql` # 2. use the string in a context broker request and retrieve the entities. query = QueryString(qs=("refBuilding", "==", building.id)) for entity in cbc.get_entity_list(q=query): print(f"All entities referencing the building: " f"\n {entity.json(indent=2)}\n") # ToDo: create a filter request that retrieves all entities from the # server`that have `hasZone' attribute that references your thermal zone # by using the FIWARE's simple query language. # `filip.utils.simple_ql` module helps you to validate your query string # 1. prepare the query string using the `filip.utils.simple_ql` # 2. use the string in a context broker request and retrieve the entities. query = QueryString(qs=("hasZone", "==", thermal_zone.id)) for entity in cbc.get_entity_list(q=query): print(f"All entities referencing the thermal zone: " f"\n {entity.json(indent=2)} \n") # write entities to file and clear server state
attr_t_amb = weather_station.get_attribute( attribute_name="temperature" ) attr_t_amb.metadata = metadata_t_amb weather_station.update_attribute(attribute=attr_t_amb) metadata_t_zone = NamedMetadata(name="unitCode", type="Text", value=code) attr_t_zone = zone_temperature_sensor.get_attribute( attribute_name="temperature") attr_t_zone.metadata = metadata_t_zone zone_temperature_sensor.update_attribute(attribute=attr_t_zone) # currently adding metadata via updating does not work perfectly. # Therefore, we do a delete and update iotac.delete_device(device_id=weather_station.device_id) iotac.post_device(device=weather_station) iotac.delete_device(device_id=zone_temperature_sensor.device_id) iotac.post_device(device=zone_temperature_sensor) iotac.delete_device(device_id=heater.device_id) iotac.post_device(device=heater) # ToDo: Retrieve all ContextEntites and print them entities = cbc.get_entity_list() for entity in entities: print(entity.json(indent=2)) clear_iot_agent(url=IOTA_URL, fiware_header=fiware_header) clear_context_broker(url=CB_URL, fiware_header=fiware_header)
class ControllerPanel: def __init__(self): # initialize controller parameters (in dict) self.params = self.initialize_params() # FIWARE parameters self.cb_url = os.getenv("CB_URL", "http://localhost:1026") self.entity_id = None # will be read on the web GUI self.entity_type = "PID_Controller" self.service = os.getenv("FIWARE_SERVICE", '') self.service_path = os.getenv("FIWARE_SERVICE_PATH", '') # Create the fiware header fiware_header = FiwareHeader(service=self.service, service_path=self.service_path) # Create orion context broker client self.ORION_CB = ContextBrokerClient(url=self.cb_url, fiware_header=fiware_header) # initial pid controller list self.controller_list = [] try: self.refresh_list() except: pass # initialize gui window sg.theme("DarkBlue") pid_id_bar = [[ sg.Text("Controller ID", size=(10, 1)), sg.Combo(self.controller_list, key="controller_list"), sg.Button("Refresh") ]] param_bars = [[ sg.Text(param.capitalize(), size=(10, 1)), sg.InputText(self.params[param], key=param) ] for param in self.params.keys()] io_bars = [[sg.Button("Send"), sg.Button("Read")]] layout = pid_id_bar + param_bars + io_bars self.window = sg.Window("PID controller", layout, web_port=80, web_start_browser=True) def gui_update(self): """Update the shown text on web GUI""" # update parameter values for param in self.params.keys(): self.window[param].update(self.params[param]) self.window["controller_list"].Update(values=self.controller_list) self.window["controller_list"].Update(value=self.entity_id) def gui_loop(self): """GUI main loop""" try: while True: event, values = self.window.read(timeout=1000) self.entity_id = values["controller_list"] if event in (sg.WINDOW_CLOSED, None): break elif event == "Send": self.send(values) elif event == "Read": print("Read", flush=True) self.read() elif event == "Refresh": self.refresh_list() self.gui_update() finally: print("panel loop fails") self.window.close() os.abort() def read(self): """Read parameter values from context broker""" try: params_update = self.initialize_params() for param in self.params.keys(): params_update[param] = float( self.ORION_CB.get_attribute_value( entity_id=self.entity_id, entity_type=self.entity_type, attr_name=param)) self.params = params_update except requests.exceptions.HTTPError as err: msg = err.args[0] if "NOT FOUND" not in msg.upper(): raise print("Cannot find controller entity") self.params = self.initialize_params() finally: self.gui_update() def send(self, params): """Send new parameter values to context broker""" for param in self.params.keys(): try: value = float(params[param]) self.ORION_CB.update_attribute_value( entity_id=self.entity_id, entity_type=self.entity_type, attr_name=param, value=value) except ValueError: print( f"Wrong value type of {param}: {params[param]}. Must be numeric!" ) def refresh_list(self): """Refresh the controller list""" entity_list = self.ORION_CB.get_entity_list( entity_types=[self.entity_type]) if entity_list: list_new = [controller.id for controller in entity_list] else: list_new = [] if all([isinstance(controller_id, str) for controller_id in list_new]) or not list_new: self.controller_list = list_new @staticmethod def initialize_params(): """Initialize the values of all control parameters""" # initialize controller parameters shown on panel params = { "Kp": "Proportional gain", "Ki": "Integral gain", "Kd": "Derivative gain", "lim_low": "Lower limit of output", "lim_upper": "Upper limit of output", "setpoint": "The set point of control variable" } return params