Custom Component , RESTful Sensor, How to get the Data in HA?

Hi there,

I’m trying to build a custom component using a RESTful Sensor to collect Data from a JSON API.

My Problem is, that I do not understand, how to map the Data to Home Assistant.

That’s what I have so far:

class JSONRestSensor(Entity):

    """Implementation of a REST sensor."""

    def __init__(self, hass, rest, name, unit_of_measurement, value_template):

        """Initialize the REST sensor."""

        self._hass = hass

        self.rest = rest

        self._name = name

        self._attributes = {}

        self._state = STATE_UNKNOWN

        self._unit_of_measurement = unit_of_measurement

        self._value_template = value_template

        self.update()

    @property

    def name(self):

        """Return the name of the sensor."""

        return self._name

    @property

    def unit_of_measurement(self):

        """Return the unit the value is expressed in."""

        return self._unit_of_measurement

    @property

    def state(self):

        """Return the state of the device."""

        return self._state

    def update(self):

        """Get the latest data from REST API and update the state."""

        self.rest.update()

        value = self.rest.data

        if value is None:

            value = STATE_UNKNOWN

        self._state = value

        """ Parse the return text as JSON and save the json as an attribute. """

        try:

            attributes = json.loads(value)

            if isinstance(attributes["Data"]["Inputs"], list):

                _LOGGER.debug("Parsed attributes form a list. Adding it as 'list'")

                self._attributes["list"] = attributes["Data"]["Inputs"]

            """Create a single sensor for every transmitted value"""

            """collect them in a list to create a group containing them later"""

            sensor_list = []

            """Iterate over all sensors"""

            for sensorobj in self._attributes["list"]:

                _sensor = sensorobj

                _LOGGER.debug("Sensor found %s" % _sensor["Number"])

                """differentiate between analog (value) and digital (on/off) sensors, also skip time value"""

                if _sensor["AD"] == "A":

                    entity_id = "sensor.uvr16x2_data_logger_%s" % (_sensor["Number"])

                    _sensor["icon"] = "mdi:thermometer"

                elif _sensor["AD"] == "D":

                    entity_id = "binary_sensor.uvr16x2_data_logger_%s" % (

                        _sensor["Number"]

                    )

                elif "time" in _sensor:

                    continue

                else:

                    entity_id = "sensor.uvr16x2_data_logger_%s" % (_sensor["Number"])

                """do the adding"""

                self._hass.states.set(entity_id, _sensor["Value"]["Value"], _sensor)

                sensor_list.append(entity_id)

            self._hass.states.set(

                "group.uvrlog_data_logger",

                "Running",

                {

                    "entity_id": sensor_list,

                    "friendly_name": self._name,

                    "icon": "mdi:radiator",

                },

            )

            """Set yourself as hidden"""

            self._attributes["hidden"] = "true"

        except json.JSONDecodeError:

            self._attributes = {}

            pass

    @property

    def state_attributes(self):

        """Return the attributes of the entity.

        Provide the parsed JSON data (if any).

        """

        return self._attributes

class JSONRestData(object):

    """Class for handling the data retrieval."""

    def __init__(self, method, resource, auth, headers, data, verify_ssl):

        """Initialize the data object."""

        self._request = requests.Request(

            method, resource, headers=headers, auth=auth, data=data

        ).prepare()

        self._verify_ssl = verify_ssl

        self.data = None

    def update(self):

        """Get the latest data from REST service with provided method."""

        try:

            with requests.Session() as sess:

                response = sess.send(self._request, timeout=10, verify=self._verify_ssl)

            self.data = response.text

        except requests.exceptions.RequestException:

            _LOGGER.error("Error fetching data: %s", self._request)

            self.data = None

This is my Data:

{
  "Data": {
    "Inputs": [
      {
        "Number": 0,
        "Description": "T.Heizkreis VL",
        "AD": "A",
        "Value": {
          "Value": 39.8,
          "Unit": "°C"
        }
      },
      {
        "Number": 1,
        "Description": "T.Kessel VL",
        "AD": "A",
        "Value": {
          "Value": 70.1,
          "Unit": "°C"
        }
      },
      {
        "Number": 2,
        "Description": "T.Solar RL",
        "AD": "A",
        "Value": {
          "Value": 49,
          "Unit": "°C"
        }
      },
      {
        "Number": 3,
        "Description": "T.Kessel VL",
        "AD": "A",
        "Value": {
          "Value": 32.5,
          "Unit": "°C"
        }
      },

Now, how do I tell Home Assistant that friendly_name is Description from JSON Data, value is [Value][Value] an so on?

I hope my question is understandable andyou can help.

friendly_name is the name property.
If you don’t want the entity_id being based on the name, override self.entity_id