def setUp(self) -> None: self.fiware_header = FiwareHeader( service=settings.FIWARE_SERVICE, service_path=settings.FIWARE_SERVICEPATH) clear_all(fiware_header=self.fiware_header, cb_url=settings.CB_URL, iota_url=settings.IOTA_JSON_URL) self.service_group1 = ServiceGroup(entity_type='Thing', resource='/iot/json', apikey=str(uuid4())) self.service_group2 = ServiceGroup(entity_type='OtherThing', resource='/iot/json', apikey=str(uuid4())) self.device = { "device_id": "test_device", "service": self.fiware_header.service, "service_path": self.fiware_header.service_path, "entity_name": "test_entity", "entity_type": "test_entity_type", "timezone": 'Europe/Berlin', "timestamp": None, "apikey": "1234", "endpoint": None, "transport": 'HTTP', "expressionLanguage": None } self.client = IoTAClient( url=settings.IOTA_JSON_URL, fiware_header=self.fiware_header)
def test_metadata(self): """ Test for metadata works but the api of iot agent-json seems not working correctly Returns: None """ metadata = {"accuracy": {"type": "Text", "value": "+-5%"}} attr = DeviceAttribute(name="temperature", object_id="temperature", type="Number", metadata=metadata) device = Device(**self.device) device.device_id = "device_with_meta" device.add_attribute(attribute=attr) logger.info(device.json(indent=2)) with IoTAClient( url=settings.IOTA_JSON_URL, fiware_header=self.fiware_header) as client: client.post_device(device=device) logger.info(client.get_device(device_id=device.device_id).json( indent=2, exclude_unset=True)) with ContextBrokerClient( url=settings.CB_URL, fiware_header=self.fiware_header) as client: logger.info(client.get_entity(entity_id=device.entity_name).json( indent=2))
def __init__(self, config: Union[str, Path, HttpClientConfig, Dict] = None, session: Session = None, fiware_header: FiwareHeader = None, **kwargs): """ Constructor for master client Args: config (Union[str, Path, Dict]): Configuration object session (request.Session): Session object fiware_header (FiwareHeader): Fiware header **kwargs: Optional arguments that ``request`` takes. """ if config: self.config = config else: self.config = HttpClientConfig() super().__init__(session=session, fiware_header=fiware_header, **kwargs) # initialize sub clients self.cb = ContextBrokerClient(url=self.config.cb_url, session=self.session, fiware_header=self.fiware_headers, **self.kwargs) self.iota = IoTAClient(url=self.config.iota_url, session=self.session, fiware_header=self.fiware_headers, **self.kwargs) self.timeseries = QuantumLeapClient(url=self.config.ql_url, session=self.session, fiware_header=self.fiware_headers, **self.kwargs) # from here on deprecated? auth_types = { 'basicauth': self.__http_basic_auth, 'digestauth': self.__http_digest_auth } # 'oauth2': self.__oauth2} if self.config.auth: assert self.config.auth['type'].lower() in auth_types.keys() self.__get_secrets_file(path=self.config.auth['secret']) auth_types[self.config.auth['type']]() self.__secrets = { "username": None, "password": None, "client_id": None, "client_secret": None }
def clear_iot_agent(url: str, fiware_header: FiwareHeader): """ Function deletes all device groups and devices for a given fiware header Args: url: Url of the context broker service fiware_header: header of the tenant Returns: None """ # create client client = IoTAClient(url=url, fiware_header=fiware_header) # clear registrations for device in client.get_device_list(): client.delete_device(device_id=device.device_id) assert len(client.get_device_list()) == 0 # clear groups for group in client.get_group_list(): client.delete_group(resource=group.resource, apikey=group.apikey) assert len(client.get_group_list()) == 0
def get_iota_client(instance_header: InstanceHeader) -> IoTAClient: """Get the correct IotaClient to be used with the given header Args: instance_header (InstanceHeader): Header to be used with client Returns: IoTAClient """ if instance_header.ngsi_version == NgsiVersion.v2: return IoTAClient( url=instance_header.iota_url, fiware_header=instance_header.get_fiware_header()) else: # todo LD raise Exception("FiwareVersion not yet supported")
class TestAgent(unittest.TestCase): def setUp(self) -> None: self.fiware_header = FiwareHeader( service=settings.FIWARE_SERVICE, service_path=settings.FIWARE_SERVICEPATH) clear_all(fiware_header=self.fiware_header, cb_url=settings.CB_URL, iota_url=settings.IOTA_JSON_URL) self.service_group1 = ServiceGroup(entity_type='Thing', resource='/iot/json', apikey=str(uuid4())) self.service_group2 = ServiceGroup(entity_type='OtherThing', resource='/iot/json', apikey=str(uuid4())) self.device = { "device_id": "test_device", "service": self.fiware_header.service, "service_path": self.fiware_header.service_path, "entity_name": "test_entity", "entity_type": "test_entity_type", "timezone": 'Europe/Berlin', "timestamp": None, "apikey": "1234", "endpoint": None, "transport": 'HTTP', "expressionLanguage": None } self.client = IoTAClient( url=settings.IOTA_JSON_URL, fiware_header=self.fiware_header) def test_get_version(self): with IoTAClient( url=settings.IOTA_JSON_URL, fiware_header=self.fiware_header) as client: self.assertIsNotNone(client.get_version()) def test_service_group_model(self): pass @clean_test(fiware_service=settings.FIWARE_SERVICE, fiware_servicepath=settings.FIWARE_SERVICEPATH, iota_url=settings.IOTA_JSON_URL) def test_service_group_endpoints(self): self.client.post_groups(service_groups=[self.service_group1, self.service_group2]) groups = self.client.get_group_list() with self.assertRaises(requests.RequestException): self.client.post_groups(groups, update=False) self.client.get_group(resource=self.service_group1.resource, apikey=self.service_group1.apikey) def test_device_model(self): device = Device(**self.device) self.assertEqual(self.device, device.dict(exclude_unset=True)) @clean_test(fiware_service=settings.FIWARE_SERVICE, fiware_servicepath=settings.FIWARE_SERVICEPATH, cb_url=settings.CB_URL, iota_url=settings.IOTA_JSON_URL) def test_device_endpoints(self): """ Test device creation """ with IoTAClient( url=settings.IOTA_JSON_URL, fiware_header=self.fiware_header) as client: client.get_device_list() device = Device(**self.device) attr = DeviceAttribute(name='temperature', object_id='t', type='Number', entity_name='test') attr_command = DeviceCommand(name='open') attr_lazy = LazyDeviceAttribute(name='pressure', object_id='p', type='Text', entity_name='pressure') attr_static = StaticDeviceAttribute(name='hasRoom', type='Relationship', value='my_partner_id') device.add_attribute(attr) device.add_attribute(attr_command) device.add_attribute(attr_lazy) device.add_attribute(attr_static) client.post_device(device=device) device_res = client.get_device(device_id=device.device_id) self.assertEqual(device.dict(exclude={'service', 'service_path', 'timezone'}), device_res.dict(exclude={'service', 'service_path', 'timezone'})) self.assertEqual(self.fiware_header.service, device_res.service) self.assertEqual(self.fiware_header.service_path, device_res.service_path) @clean_test(fiware_service=settings.FIWARE_SERVICE, fiware_servicepath=settings.FIWARE_SERVICEPATH, cb_url=settings.CB_URL, iota_url=settings.IOTA_JSON_URL) def test_metadata(self): """ Test for metadata works but the api of iot agent-json seems not working correctly Returns: None """ metadata = {"accuracy": {"type": "Text", "value": "+-5%"}} attr = DeviceAttribute(name="temperature", object_id="temperature", type="Number", metadata=metadata) device = Device(**self.device) device.device_id = "device_with_meta" device.add_attribute(attribute=attr) logger.info(device.json(indent=2)) with IoTAClient( url=settings.IOTA_JSON_URL, fiware_header=self.fiware_header) as client: client.post_device(device=device) logger.info(client.get_device(device_id=device.device_id).json( indent=2, exclude_unset=True)) with ContextBrokerClient( url=settings.CB_URL, fiware_header=self.fiware_header) as client: logger.info(client.get_entity(entity_id=device.entity_name).json( indent=2)) 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) def test_update_device(self): """ Test the methode: update_device of the iota client """ device = Device(**self.device) device.endpoint = "http://test.com" device.transport = "MQTT" device.add_attribute(DeviceAttribute( name="Att1", object_id="o1", type=DataType.STRUCTUREDVALUE)) device.add_attribute(StaticDeviceAttribute( name="Stat1", value="test", type=DataType.STRUCTUREDVALUE)) device.add_attribute(StaticDeviceAttribute( name="Stat2", value="test", type=DataType.STRUCTUREDVALUE)) device.add_command(DeviceCommand(name="Com1")) # use update_device to post self.client.update_device(device=device, add=True) cb_client = ContextBrokerClient(url=settings.CB_URL, fiware_header=self.fiware_header) # test if attributes exists correctly live_entity = cb_client.get_entity(entity_id=device.entity_name) live_entity.get_attribute("Att1") live_entity.get_attribute("Com1") live_entity.get_attribute("Com1_info") live_entity.get_attribute("Com1_status") self.assertEqual(live_entity.get_attribute("Stat1").value, "test") # change device attributes and update device.get_attribute("Stat1").value = "new_test" device.delete_attribute(device.get_attribute("Stat2")) device.delete_attribute(device.get_attribute("Att1")) device.delete_attribute(device.get_attribute("Com1")) device.add_attribute(DeviceAttribute( name="Att2", object_id="o1", type=DataType.STRUCTUREDVALUE)) device.add_attribute(StaticDeviceAttribute( name="Stat3", value="test3", type=DataType.STRUCTUREDVALUE)) device.add_command(DeviceCommand(name="Com2")) # device.endpoint = "http://localhost:8080" self.client.update_device(device=device) # test if update does what it should, for the device. It does not # change the entity completely: live_device = self.client.get_device(device_id=device.device_id) with self.assertRaises(KeyError): live_device.get_attribute("Att1") with self.assertRaises(KeyError): live_device.get_attribute("Com1_info") with self.assertRaises(KeyError): live_device.get_attribute("Stat2") self.assertEqual(live_device.get_attribute("Stat1").value, "new_test") live_device.get_attribute("Stat3") live_device.get_command("Com2") live_device.get_attribute("Att2") cb_client.close() def test_patch_device(self): """ Test the methode: patch_device of the iota client """ device = Device(**self.device) device.endpoint = "http://test.com" device.transport = "MQTT" device.add_attribute(DeviceAttribute( name="Att1", object_id="o1", type=DataType.STRUCTUREDVALUE)) device.add_attribute(StaticDeviceAttribute( name="Stat1", value="test", type=DataType.STRUCTUREDVALUE)) device.add_attribute(StaticDeviceAttribute( name="Stat2", value="test", type=DataType.STRUCTUREDVALUE)) device.add_command(DeviceCommand(name="Com1")) # use patch_device to post self.client.patch_device(device=device) cb_client = ContextBrokerClient(url=settings.CB_URL, fiware_header=self.fiware_header) # test if attributes exists correctly live_entity = cb_client.get_entity(entity_id=device.entity_name) live_entity.get_attribute("Att1") live_entity.get_attribute("Com1") live_entity.get_attribute("Com1_info") live_entity.get_attribute("Com1_status") self.assertEqual(live_entity.get_attribute("Stat1").value, "test") # change device attributes and update device.get_attribute("Stat1").value = "new_test" device.delete_attribute(device.get_attribute("Stat2")) device.delete_attribute(device.get_attribute("Att1")) device.delete_attribute(device.get_attribute("Com1")) device.add_attribute(DeviceAttribute( name="Att2", object_id="o1", type=DataType.STRUCTUREDVALUE)) device.add_attribute(StaticDeviceAttribute( name="Stat3", value="test3", type=DataType.STRUCTUREDVALUE)) device.add_command(DeviceCommand(name="Com2")) self.client.patch_device(device=device, cb_url=settings.CB_URL) # test if update does what it should, for the device. It does not # change the entity completely: live_entity = cb_client.get_entity(entity_id=device.entity_name) with self.assertRaises(KeyError): live_entity.get_attribute("Att1") with self.assertRaises(KeyError): live_entity.get_attribute("Com1_info") with self.assertRaises(KeyError): live_entity.get_attribute("Stat2") self.assertEqual(live_entity.get_attribute("Stat1").value, "new_test") live_entity.get_attribute("Stat3") live_entity.get_attribute("Com2_info") live_entity.get_attribute("Att2") # test update where device information were changed device_settings = {"endpoint": "http://localhost:7071", "device_id": "new_id", "entity_name": "new_name", "entity_type": "new_type", "timestamp": False, "apikey": "zuiop", "protocol": "HTTP", "transport": "HTTP"} for key, value in device_settings.items(): device.__setattr__(key, value) self.client.patch_device(device=device) live_device = self.client.get_device(device_id=device.device_id) self.assertEqual(live_device.__getattribute__(key), value) cb_client.close() def tearDown(self) -> None: """ Cleanup test server """ self.client.close() clear_all(fiware_header=self.fiware_header, cb_url=settings.CB_URL, iota_url=settings.IOTA_JSON_URL)
sim_model = SimulationModel(t_start=T_SIM_START, t_end=T_SIM_END, temp_max=TEMPERATURE_MAX, temp_min=TEMPERATURE_MIN, temp_start=TEMPERATURE_ZONE_START) # define lists to store historical data history_weather_station = [] history_zone_temperature_sensor = [] history_heater = [] # Create clients and restore devices and groups from file groups = parse_file_as(List[ServiceGroup], READ_GROUPS_FILEPATH) devices = parse_file_as(List[Device], READ_DEVICES_FILEPATH) cbc = ContextBrokerClient(url=CB_URL, fiware_header=fiware_header) iotac = IoTAClient(url=IOTA_URL, fiware_header=fiware_header) iotac.post_groups(service_groups=groups) iotac.post_devices(devices=devices) # ToDo: Get the device configurations from the server weather_station = iotac.get_device(device_id="device:001") zone_temperature_sensor = iotac.get_device(device_id="device:002") # ToDo: Get the service group configurations from the server group = iotac.get_group(resource="/iot/json", apikey=APIKEY) # ToDo: Create and additional device holding a command attribute and # post it to the IoT-Agent. It should be mapped to the `type` heater # create the simtime attribute and add during device creation t_sim = DeviceAttribute(name='simtime', object_id='t_sim',
entity_name='urn:ngsi-ld:TemperatureSensor:001', entity_type='TemperatureSensor', protocol='IoTA-JSON', transport='MQTT', apikey=APIKEY, attributes=[t_sim], commands=[]) # ToDo: Create the temperature attribute. Use the 't_zone' as `object_id`. # `object_id` specifies what key will be used in the MQTT Message payload t_zone = DeviceAttribute(name='temperature', object_id='t_zone', type="Number") zone_temperature_sensor.add_attribute(t_zone) # ToDo: Create an IoTAClient iotac = IoTAClient(url=IOTA_URL, fiware_header=fiware_header) # ToDo: Provision service group and add it to your IoTAMQTTClient iotac.post_group(service_group=service_group, update=True) # ToDo: Provision the devices at the IoTA-Agent # provision the WeatherStation device iotac.post_device(device=weather_station, update=True) # ToDo: provision the zone temperature device iotac.post_device(device=zone_temperature_sensor, update=True) # ToDo: Check in the context broker if the entities corresponding to your # devices where correctly created # ToDo: Create a context broker client cbc = ContextBrokerClient(url=CB_URL, fiware_header=fiware_header) # Get WeatherStation entity print(cbc.get_entity(weather_station.entity_name).json(indent=2)) # Get ZoneTemperatureSensor entity