def run(self, registry): from liota.entities.devices.simulated_device import SimulatedDevice from liota.entities.metrics.metric import Metric import copy # Acquire resources from registry iotcc = registry.get("iotcc") # Creating a copy of edge_system object to keep original object "clean" iotcc_edge_system = copy.copy(registry.get("iotcc_edge_system")) # Get values from configuration file config_path = registry.get("package_conf") config = {} execfile(config_path + '/sampleProp.conf', config) # Register device ram_device = SimulatedDevice(config['DeviceName'], "Device-RAM") reg_ram_device = iotcc.register(ram_device) iotcc.set_properties(reg_ram_device, config['DevicePropList']) iotcc.create_relationship(iotcc_edge_system, reg_ram_device) # Create metrics self.metrics = [] mem_free_metric = Metric(name="Memory Free", unit=None, interval=10, sampling_function=read_mem_free) reg_mem_free_metric = iotcc.register(mem_free_metric) iotcc.create_relationship(reg_ram_device, reg_mem_free_metric) reg_mem_free_metric.start_collecting() self.metrics.append(reg_mem_free_metric) registry.register("reg_ram_device", reg_ram_device)
def test_implementation_get_entity_hierarchy_device_metric(self): """ Test case to check get_entity_entity_hierarchy() for RegisteredEdgeSystem->RegisteredDevice->RegisteredMetric :return: None """ # Register the edge registered_entity = self.aws.register(self.edge_system) # Creating Simulated Device test_sensor = SimulatedDevice("TestSensor") # Registering Device and creating Parent-Child relationship reg_test_sensor = self.aws.register(test_sensor) self.aws.create_relationship(registered_entity, reg_test_sensor) # Creating test Metric test_metric = Metric(name="Test_Metric", unit=ureg.degC, interval=10, aggregation_size=2, sampling_function=sampling_function) registered_metric = self.aws.register(test_metric) # Creating the parent-child relationship self.aws.create_relationship(reg_test_sensor, registered_metric) # Getting the parent child relationship array from registered metric entity_hierarchy = get_entity_hierarchy(registered_metric) self.assertSequenceEqual( [ registered_entity.ref_entity.name, reg_test_sensor.ref_entity.name, registered_metric.ref_entity.name ], entity_hierarchy, "Check the implementation of _get_entity_hierarchy for " "RegisteredEdgeSystem->RegisteredDevice->RegisteredMetric")
def run(self, registry): from liota.entities.devices.simulated_device import SimulatedDevice from liota.entities.metrics.metric import Metric import copy # Acquire resources from registry self.iotcc = registry.get("iotcc_mqtt") # Creating a copy of edge_system object to keep original object "clean" self.iotcc_edge_system = copy.copy(registry.get("iotcc_mqtt_edge_system")) # Get values from configuration file config_path = registry.get("package_conf") self.config = read_user_config(config_path + '/sampleProp.conf') # Register device ram_device = SimulatedDevice(self.config['DeviceName'], "Device-RAM") self.reg_ram_device = self.iotcc.register(ram_device) self.iotcc.set_properties(self.reg_ram_device, self.config['DevicePropList']) self.iotcc.create_relationship(self.iotcc_edge_system, self.reg_ram_device) # Create metrics self.metrics = [] mem_free_metric = Metric( name="Memory Free", unit=None, interval=10, sampling_function=read_mem_free ) reg_mem_free_metric = self.iotcc.register(mem_free_metric) self.iotcc.create_relationship(self.reg_ram_device, reg_mem_free_metric) reg_mem_free_metric.start_collecting() self.metrics.append(reg_mem_free_metric) # Use the iotcc_device_name as identifier in the registry to easily refer the device in other packages registry.register("reg_ram_device_mqtt", self.reg_ram_device)
reg_edge_system = aws.register(edge_system) # Creating CPU Metric cpu_utilization = Metric(name="CPUUtilization", unit=None, interval=10, aggregation_size=2, sampling_function=read_cpu_utilization) # Registering Metric and creating Parent-Child relationship reg_cpu_utilization = aws.register(cpu_utilization) aws.create_relationship(reg_edge_system, reg_cpu_utilization) # Publishing Registered CPU Utilization Metric to AWS reg_cpu_utilization.start_collecting() # Creating Simulated Device dht_sensor = SimulatedDevice("SimulatedDHTSensor") # Registering Device and creating Parent-Child relationship reg_dht_sensor = aws.register(dht_sensor) aws.create_relationship(reg_edge_system, reg_dht_sensor) # Creating Temperature Metric temp_metric = Metric(name="LivingRoomTemperature", entity_type="Metric", unit=ureg.degC, interval=1, aggregation_size=5, sampling_function=get_living_room_temperature) # Registering Metric and creating Parent-Child relationship reg_temp_metric = aws.register(temp_metric) aws.create_relationship(reg_dht_sensor, reg_temp_metric) # Publishing Registered Temperature Metric to AWS reg_temp_metric.start_collecting()
interval=5, sampling_function=read_network_bytes_received) reg_network_bits_received_metric = iotcc.register( network_bits_received_metric) iotcc.create_relationship(reg_edge_system, reg_network_bits_received_metric) reg_network_bits_received_metric.start_collecting() # Here we are showing how to create a device object, registering it in IoTCC, and setting properties on it # Since there are no attached devices are as simulating one by considering RAM as separate from the IoT System # The agent makes possible many different data models # arguments: # device name # Read or Write # another Resource in IoTCC of which the should be the child of a parent-child relationship among Resources ram_device = SimulatedDevice(config['DeviceName'], "Device-RAM") reg_ram_device = iotcc.register(ram_device) iotcc.create_relationship(reg_edge_system, reg_ram_device) # note that the location of this 'device' is different from the location of the IoTCC. It's not really different # but just an example of how one might create a device different from the IoTCC mem_free_metric = Metric(name="Memory Free", unit=None, interval=10, sampling_function=read_mem_free) reg_mem_free_metric = iotcc.register(mem_free_metric) iotcc.create_relationship(reg_ram_device, reg_mem_free_metric) reg_mem_free_metric.start_collecting() except RegistrationFailure: print "Registration to IOTCC failed"
def run(self, registry): import copy import pint from liota.lib.transports.mqtt import MqttMessagingAttributes from liota.entities.metrics.metric import Metric from liota.entities.devices.simulated_device import SimulatedDevice # create a pint unit registry ureg = pint.UnitRegistry() # Acquire resources from registry aws_iot = registry.get("aws_iot") aws_iot_edge_system = copy.copy(registry.get("aws_iot_edge_system")) # Get values from configuration file config_path = registry.get("package_conf") config = {} execfile(config_path + '/sampleProp.conf', config) # Create metrics self.metrics = [] # Creating CPU Metric cpu_utilization = Metric(name="CPUUtilization", unit=None, interval=10, aggregation_size=2, sampling_function=read_cpu_utilization) # Registering Metric and creating Parent-Child relationship reg_cpu_utilization = aws_iot.register(cpu_utilization) aws_iot.create_relationship(aws_iot_edge_system, reg_cpu_utilization) # Publish topic for this Metric reg_cpu_utilization.msg_attr = MqttMessagingAttributes( pub_topic=config['CustomPubTopic']) # Publishing Registered CPU Utilization Metric to AWSIoT Dcc reg_cpu_utilization.start_collecting() self.metrics.append(reg_cpu_utilization) # Creating Simulated Device dht_sensor = SimulatedDevice("SimulatedDHTSensor") # Registering Device and creating Parent-Child relationship reg_dht_sensor = aws_iot.register(dht_sensor) aws_iot.create_relationship(aws_iot_edge_system, reg_dht_sensor) # Creating Temperature Metric temp_metric = Metric(name="LivingRoomTemperature", entity_type="Metric", unit=ureg.degC, interval=1, aggregation_size=5, sampling_function=get_living_room_temperature) # Registering Metric and creating Parent-Child relationship reg_temp_metric = aws_iot.register(temp_metric) aws_iot.create_relationship(reg_dht_sensor, reg_temp_metric) # Publish topic for this Metric reg_temp_metric.msg_attr = MqttMessagingAttributes( pub_topic=config['LivingRoomTemperatureTopic']) # Publishing Registered Temperature Metric to AWSIoT Dcc reg_temp_metric.start_collecting() self.metrics.append(reg_temp_metric) # Creating Humidity Metric hum_metric = Metric(name="LivingRoomHumidity", entity_type="Metric", unit=None, interval=1, aggregation_size=5, sampling_function=get_living_room_humidity) # Registering Metric and creating Parent-Child relationship reg_hum_metric = aws_iot.register(hum_metric) aws_iot.create_relationship(reg_dht_sensor, reg_hum_metric) # Publish topic for this Metric reg_hum_metric.msg_attr = MqttMessagingAttributes( pub_topic=config['LivingRoomHumidityTopic']) # Publishing Registered Humidity Metric to AWSIoT Dcc reg_hum_metric.start_collecting() self.metrics.append(reg_hum_metric) # Creating Simulated Device light_sensor = SimulatedDevice("SimDigLightSensor") # Registering Device and creating Parent-Child relationship reg_light_sensor = aws_iot.register(light_sensor) aws_iot.create_relationship(aws_iot_edge_system, reg_light_sensor) # Creating Light Metric light_metric = Metric(name="LivingRoomLight", entity_type="Metric", unit=None, interval=10, aggregation_size=1, sampling_function=get_living_room_luminance) # Registering Metric and creating Parent-Child relationship reg_light_metric = aws_iot.register(light_metric) aws_iot.create_relationship(reg_light_sensor, reg_light_metric) # Publish topic for this Metric reg_light_metric.msg_attr = MqttMessagingAttributes( pub_topic=config['LivingRoomLightTopic']) # Publishing Registered Light Metric to AWSIoT DCC reg_light_metric.start_collecting() self.metrics.append(reg_light_metric)
def run(self, registry): # The execution function of a liota package. # Acquires "iotcc_mqtt" and "iotcc_mqtt_edge_system" from registry then register five devices # and publishes device metrics to the DCC # :param registry: the instance of ResourceRegistryPerPackage of the package # :return: from liota.entities.devices.simulated_device import SimulatedDevice from liota.entities.metrics.metric import Metric import copy # Acquire resources from registry self.iotcc = registry.get("iotcc_mqtt") # Creating a copy of edge_system object to keep original object "clean" self.iotcc_edge_system = copy.copy( registry.get("iotcc_mqtt_edge_system")) self.reg_devices = [] self.metrics = [] num_devices = 1 try: # CHANGETHIS # Register device: # Here, you are registering a new device (Data Source) # Change the values in the quotes below in SimulatedDevice device = SimulatedDevice("Temperature001", "TemperatureSensor") log.info("Registration Started for Device {0}".format(device.name)) # Device Registration attempts reg_attempts = 0 # Started Device Registration attempts while reg_attempts <= retry_attempts: try: reg_device = self.iotcc.register(device) break except Exception as e: if reg_attempts == retry_attempts: raise reg_attempts += 1 log.error( 'Trying Device {0} Registration failed with following error - {1}' .format(device.name, str(e))) log.info('{0} Device Registration: Attempt: {1}'.format( device.name, str(reg_attempts))) time.sleep(delay_retries) self.reg_devices.append(reg_device) # Attempts to set device relationship with edge system relationship_attempts = 0 while relationship_attempts <= retry_attempts: try: self.iotcc.create_relationship(self.iotcc_edge_system, reg_device) break except Exception as e: if relationship_attempts == retry_attempts: raise relationship_attempts += 1 log.error( 'Trying Device {0} relationship with Edge System failed with following error - {1}' .format(device.name, str(e))) log.info('{0} Device Relationship: Attempt: {1}'.format( device.name, str(relationship_attempts))) time.sleep(delay_retries) # CHANGETHIS # Use the device name as identifier in the registry to easily refer the device in other packages # Modify the device_registry_name based on your need. device_registry_name = "Temperature_001" registry.register(device_registry_name, reg_device) # Setting multiple properties by passing Dictonary object for Devices with the retry attempts # in case of exceptions prop_attempts = 0 while prop_attempts <= retry_attempts: try: # CHANGETHIS # PROPERTIES OF THE DEVICE: # Enter Key-Value pairs based on your need. # It could be any Key and any Value as long as it is a string. self.iotcc.set_properties( reg_device, { "Country": "USA", "State": "Georgia", "City": "Atlanta", "Location": "AirWatch HQ", "Building": "Perimeter", "Floor": "Fifth Floor" }) break except Exception as e: prop_attempts = prop_attempts + 1 log.error( 'Exception while setting property for Device {0} - {1}' .format((device.name, str(e)))) log.info( 'Trying setting properties for Device {0}: Attempt - {1}' .format(device.name, str(prop_attempts))) time.sleep(delay_retries) try: # CHANGETHIS # Registering Metric for Device: # Modify metric_name, and sampling function, interval and aggregation_size # in metric_simulated_received. # Copy and paste the try section to add more metrics. # REG_METRIC ++ metric_name = "Temperature_C" metric_simulated_received = Metric( name=metric_name, unit=None, interval=5, aggregation_size=1, sampling_function=read_temperature) reg_metric_simulated_received = self.iotcc.register( metric_simulated_received) self.iotcc.create_relationship(reg_device, reg_metric_simulated_received) reg_metric_simulated_received.start_collecting() self.metrics.append(reg_metric_simulated_received) except Exception as e: log.error( 'Exception while loading metric {0} for device {1} - {2}'. format(metric_name, device.name, str(e))) except Exception: log.info("Device Registration and Metrics loading failed") raise
def run(self, registry): """ The execution function of a liota package. Acquires "iotcc_mqtt" and "iotcc_mqtt_edge_system" from registry then register five devices and publishes device metrics to the DCC :param registry: the instance of ResourceRegistryPerPackage of the package :return: """ from liota.entities.devices.simulated_device import SimulatedDevice from liota.entities.metrics.metric import Metric import copy # Acquire resources from registry self.iotcc = registry.get("iotcc_mqtt") # Creating a copy of edge_system object to keep original object "clean" self.iotcc_edge_system = copy.copy( registry.get("iotcc_mqtt_edge_system")) self.reg_devices = [] self.metrics = [] num_devices = 51 for i in range(0, num_devices): try: # Register device device = SimulatedDevice(socket.gethostname() + "-ChildDev" + str(i)) log.info("Registration Started for Device {0}".format( device.name)) # Device Registration attempts reg_attempts = 0 # Started Device Registration attempts while reg_attempts <= retry_attempts: try: reg_device = self.iotcc.register(device) break except Exception as e: if reg_attempts == retry_attempts: raise reg_attempts += 1 log.error( 'Trying Device {0} Registration failed with following error - {1}' .format(device.name, str(e))) log.info( '{0} Device Registration: Attempt: {1}'.format( device.name, str(reg_attempts))) time.sleep(delay_retries) self.reg_devices.append(reg_device) # Attempts to set device relationship with edge system relationship_attempts = 0 while relationship_attempts <= retry_attempts: try: self.iotcc.create_relationship(self.iotcc_edge_system, reg_device) break except Exception as e: if relationship_attempts == retry_attempts: raise relationship_attempts += 1 log.error( 'Trying Device {0} relationship with Edge System failed with following error - {1}' .format(device.name, str(e))) log.info( '{0} Device Relationship: Attempt: {1}'.format( device.name, str(relationship_attempts))) time.sleep(delay_retries) # Use the device name as identifier in the registry to easily refer the device in other packages device_registry_name = socket.gethostname( ) + "-ChildDev" + str(i) registry.register(device_registry_name, reg_device) # Setting multiple properties by passing Dictonary object for Devices with the retry attempts # in case of exceptions prop_attempts = 0 while prop_attempts <= retry_attempts: try: self.iotcc.set_properties( reg_device, { "Country": "USA-G", "State": "California", "City": "Palo Alto", "Location": "VMware HQ", "Building": "Promontory H Lab", "Floor": "First Floor" }) break except Exception as e: prop_attempts = prop_attempts + 1 log.error( 'Exception while setting property for Device {0} - {1}' .format((device.name, str(e)))) log.info( 'Trying setting properties for Device {0}: Attempt - {1}' .format(device.name, str(prop_attempts))) time.sleep(delay_retries) try: # Registering Metric for Device metric_name = "Simulated Metrics" metric_simulated_received = Metric( name=metric_name, unit=None, interval=300, aggregation_size=1, sampling_function=device_metric) reg_metric_simulated_received = self.iotcc.register( metric_simulated_received) self.iotcc.create_relationship( reg_device, reg_metric_simulated_received) reg_metric_simulated_received.start_collecting() self.metrics.append(reg_metric_simulated_received) except Exception as e: log.error( 'Exception while loading metric {0} for device {1} - {2}' .format(metric_name, device.name, str(e))) except Exception: log.info("Device Registration and Metrics loading failed") raise
iotcc = IotControlCenter( WebSocketDccComms(url=config['WebSocketUrl'], verify_cert=config['VerifyServerCert'], identity=ws_identity) ) try: # Register Edge System with IoT control center reg_edge_system = iotcc.register(edge_system) # these call set properties on the Resource representing the IoT System # properties are a key:value store reg_edge_system.set_properties(config['SystemPropList']) # Create kitchen device object and register it on IoTCC # Add two device names in the configurations as DeviceName1 and DeviceName2 kitchen_temperature_device = SimulatedDevice(name=config['DeviceName1']) reg_kitchen_temperature_device = iotcc.register(kitchen_temperature_device) iotcc.create_relationship(reg_edge_system, reg_kitchen_temperature_device) reg_kitchen_temperature_device.set_properties(config['DevicePropList']) # Metric Name metric_name_kitchen_temperature = "temperature.kitchen" # Create metric for kitchen temperature kitchen_temperature = Metric( name=metric_name_kitchen_temperature, unit=ureg.degC, interval=0, sampling_function=lambda: get_value(kitchen_temperature_data) )
def sub_callback(self, client, userdata, msg): #analysis topic string , I just want the pulse topic if (msg.topic.split("/").__len__() == 4) and ( msg.topic.split("/")[3] == "pulse-topic" ): # msg.topic = "pulse-account-name/pulseid/pulse/pulse-topic" #the json payload from kura, analysis it json_payload = json.loads(msg.payload)['metrics'] if json_payload: # msg.payload = "{"sentOn":1533007387525,"metrics":{"assetName":"Store-GW-03","sensor_timestamp":1533007387525,"sensor":0}}" #If new Device to be registered will be checked below if json_payload['assetName'] in device_dict.keys(): log.info("Device already registered.") for key_metric in json_payload.keys(): # Filter out the sensor not required if key_metric == "assetName": continue if key_metric.find('stamp') >= 0: continue if key_metric in msg_dict.keys(): #exist update msg msg_dict[key_metric]['msg'] = json_payload[key_metric] msg_dict[key_metric]['flag'] = 0 else: msg_dict[key_metric] = {} msg_dict[key_metric]['msg'] = json_payload[key_metric] msg_dict[key_metric]['flag'] = 1 exec(callback_func_str % (key_metric, key_metric) ) # Dynamically generating callback function try: metric_ins = Metric( name=key_metric, unit=None, interval=3, aggregation_size=1, sampling_function=eval( "metric_callback_%s" % key_metric ) # Callback function publish data to iotcc ) reg_metric = userdata['self'].iotcc.register( metric_ins) userdata['self'].iotcc.create_relationship( device_dict[json_payload['assetName']], reg_metric) reg_metric.start_collecting() userdata['self'].metrics.append(reg_metric) msg_dict[key_metric]['metric'] = reg_metric except Exception as e: log.error( 'Exception while loading metric {0} for Edge System {1}' .format(key_metric, str(e))) else: #new device enrolling log.info("New device to be registered.") try: # Register device device = SimulatedDevice(json_payload['assetName'], json_payload['assetName']) # Device Registration attempts reg_attempts = 0 # Started Device Registration attempts while reg_attempts <= retry_attempts: try: reg_device = userdata['self'].iotcc.register( device) break except Exception as e: if reg_attempts == retry_attempts: raise reg_attempts += 1 log.error( 'Trying Device {0} Registration failed with following error - {1}' .format(device.name, str(e))) log.info( '{0} Device Registration: Attempt: {1}'.format( device.name, str(reg_attempts))) time.sleep(delay_retries) userdata['self'].reg_devices.append(reg_device) # Attempts to set device relationship with edge system relationship_attempts = 0 while relationship_attempts <= retry_attempts: try: userdata['self'].iotcc.create_relationship( userdata['self'].iotcc_edge_system, reg_device) break except Exception as e: if relationship_attempts == retry_attempts: raise relationship_attempts += 1 log.error( 'Trying Device {0} relationship with Edge System failed with following error - {1}' .format(device.name, str(e))) log.info( '{0} Device Relationship: Attempt: {1}'.format( device.name, str(relationship_attempts))) time.sleep(delay_retries) # Use the device name as identifier in the registry to easily refer the device in other packages device_registry_name = json_payload['assetName'] userdata['registry'].register(device_registry_name, reg_device) # Setting multiple properties by passing Dictonary object for Devices with the retry attempts # in case of exceptions prop_attempts = 0 while prop_attempts <= retry_attempts: try: userdata['self'].iotcc.set_properties( reg_device, { "Country": "CN-B", "State": "BeiJing", "City": "China", "Location": "VMware BeiJing", "Building": "BeiJing", "Floor": "BeiJing Floor" }) break except Exception as e: prop_attempts = prop_attempts + 1 log.error( 'Exception while setting property for Device {0} - {1}' .format(device.name, str(e))) log.info( 'Trying setting properties for Device {0}: Attempt - {1}' .format(device.name, str(prop_attempts))) time.sleep(delay_retries) except Exception: log.info("Device Registration and Metrics loading failed") self.clean_up() raise device_dict[json_payload['assetName']] = reg_device else: log.info("json_payload empty") else: log.info("another topic")
def run(self, registry): import copy import pint from liota.entities.metrics.metric import Metric from liota.entities.devices.simulated_device import SimulatedDevice # create a pint unit registry ureg = pint.UnitRegistry() # Acquire resources from registry aws_iot = registry.get("aws_iot") aws_iot_edge_system = copy.copy(registry.get("aws_iot_edge_system")) # Create metrics self.metrics = [] # Creating CPU Metric cpu_utilization = Metric( name="CPUUtilization", unit=None, interval=10, aggregation_size=2, sampling_function=read_cpu_utilization ) # Registering Metric and creating Parent-Child relationship reg_cpu_utilization = aws_iot.register(cpu_utilization) aws_iot.create_relationship(aws_iot_edge_system, reg_cpu_utilization) # Publishing Registered CPU Utilization Metric to AWSIoT Dcc reg_cpu_utilization.start_collecting() self.metrics.append(reg_cpu_utilization) # Creating Simulated Device dht_sensor = SimulatedDevice("SimulatedDHTSensor") # Registering Device and creating Parent-Child relationship reg_dht_sensor = aws_iot.register(dht_sensor) aws_iot.create_relationship(aws_iot_edge_system, reg_dht_sensor) # Creating Temperature Metric temp_metric = Metric( name="LivingRoomTemperature", entity_type="Metric", unit=ureg.degC, interval=1, aggregation_size=5, sampling_function=get_living_room_temperature ) # Registering Metric and creating Parent-Child relationship reg_temp_metric = aws_iot.register(temp_metric) aws_iot.create_relationship(reg_dht_sensor, reg_temp_metric) # Publishing Registered Temperature Metric to AWSIoT Dcc reg_temp_metric.start_collecting() self.metrics.append(reg_temp_metric) # Creating Humidity Metric hum_metric = Metric( name="LivingRoomHumidity", entity_type="Metric", unit=None, interval=1, aggregation_size=5, sampling_function=get_living_room_humidity ) # Registering Metric and creating Parent-Child relationship reg_hum_metric = aws_iot.register(hum_metric) aws_iot.create_relationship(reg_dht_sensor, reg_hum_metric) # Publishing Registered Humidity Metric to AWSIoT Dcc reg_hum_metric.start_collecting() self.metrics.append(reg_hum_metric) # Creating Simulated Device light_sensor = SimulatedDevice("SimDigLightSensor") # Registering Device and creating Parent-Child relationship reg_light_sensor = aws_iot.register(light_sensor) aws_iot.create_relationship(aws_iot_edge_system, reg_light_sensor) # Creating Light Metric light_metric = Metric( name="LivingRoomLight", entity_type="Metric", unit=None, interval=10, aggregation_size=1, sampling_function=get_living_room_luminance ) # Registering Metric and creating Parent-Child relationship reg_light_metric = aws_iot.register(light_metric) aws_iot.create_relationship(reg_light_sensor, reg_light_metric) # Publishing Registered Light Metric to AWSIoT Dcc reg_light_metric.start_collecting() self.metrics.append(reg_light_metric)
def test_implementation_get_formatted_data_with_enclose_metadata_device_exception_flow( self): """ Test case to test the implementation of get_formatted_data method with enclose_metadata option. RegisteredEdgeSystem->RegisteredDevice->RegisteredMetric :return: None """ # Mock the get_formatted_data with mock.patch("liota.lib.utilities.dcc_utility.parse_unit" ) as mocked_parse_unit: # Method to be invoked on calling the parse_unit function mocked_parse_unit.side_effect = raise_exception # Register the edge registered_entity = self.aws.register(self.edge_system) # Creating Simulated Device test_sensor = SimulatedDevice("TestSensor") # Registering Device and creating Parent-Child relationship reg_test_sensor = self.aws.register(test_sensor) self.aws.create_relationship(registered_entity, reg_test_sensor) # Creating test Metric test_metric = Metric(name="Test_Metric", unit=ureg.degC, interval=10, aggregation_size=2, sampling_function=sampling_function) registered_metric = self.aws.register(test_metric) # Creating the parent-child relationship self.aws.create_relationship(reg_test_sensor, registered_metric) # Get current timestamp timestamp = getUTCmillis() registered_metric.values.put((timestamp, 10)) # Expected output without enclosed metadata expected_output = { "edge_system_name": registered_entity.ref_entity.name, "metric_name": registered_metric.ref_entity.name, "device_name": reg_test_sensor.ref_entity.name, "metric_data": [{ "value": 10, "timestamp": timestamp }], "unit": "null" } # Getting the parent child relationship array from registered metric formatted_data = get_formatted_data(registered_metric, True) # Convert json string to dict for the comparision formatted_json_data = json.loads(formatted_data) # Check two dicts are equal or not self.assertEqual( validate_json(formatted_json_data) == validate_json( expected_output), True, "Check implementation of get_formatted_data")
def test_implementation_get_formatted_data_with_enclose_metadata_device( self): """ Test case to test the implementation of get_formatted_data method with enclose_metadata option. RegisteredEdgeSystem->RegisteredDevice->RegisteredMetric :return: None """ # Register the edge registered_entity = self.aws.register(self.edge_system) # Creating Simulated Device test_sensor = SimulatedDevice("TestSensor") # Registering Device and creating Parent-Child relationship reg_test_sensor = self.aws.register(test_sensor) self.aws.create_relationship(registered_entity, reg_test_sensor) # Creating test Metric test_metric = Metric(name="Test_Metric", unit=ureg.degC, interval=10, aggregation_size=2, sampling_function=sampling_function) registered_metric = self.aws.register(test_metric) # Creating the parent-child relationship self.aws.create_relationship(reg_test_sensor, registered_metric) # Get current timestamp timestamp = getUTCmillis() registered_metric.values.put((timestamp, 10)) # Expected output without enclosed metadata expected_output = { "edge_system_name": registered_entity.ref_entity.name, "metric_name": registered_metric.ref_entity.name, "device_name": reg_test_sensor.ref_entity.name, "metric_data": [{ "value": 10, "timestamp": timestamp }], "unit": "null" } unit_tuple = parse_unit(ureg.degC) if unit_tuple[0] is None: # Base and Derived Units expected_output['unit'] = unit_tuple[1] else: # Prefixed or non-SI Units expected_output['unit'] = unit_tuple[0] + unit_tuple[1] # Getting the parent child relationship array from registered metric formatted_data = get_formatted_data(registered_metric, True) # Convert json string to dict for the comparision formatted_json_data = json.loads(formatted_data) # Check two dicts are equal or not self.assertEqual( validate_json(formatted_json_data) == validate_json( expected_output), True, "Check implementation of get_formatted_data")