Cant get my first custom integration to work (took help from Chat GPT)

Hi,

Would appriciate some helt with my first custom integration. I have programming experience but I’m new to HA and Python. So i tried to create the framework using ChatGPT (3.5 as 4 is not avalible), my thinking was to write the logic by my self after this.

What i try to accomplish is to read attributes from another sensor(Nordpool), make calculations and publish 2 states and a lot of attributes.

I have set “debug” state for this “energy_management” component in the log settings and when starting up i get the following errors in the log file:

2023-12-05 10:18:58.783 ERROR (MainThread) [homeassistant.setup] The energy_management integration does not support YAML setup, please remove it from your configuration

2023-12-05 10:18:58.783 ERROR (MainThread) [homeassistant.setup] Setup failed for custom integration energy_management: No setup or config entry setup function defined.

I have defined the custom component as a sensor and use async, is this the best setup?

I have done what i can with my very limited knowlege, would highly appriciate some guidence of how to proceed.

I added the following line in the configuration.yaml:

energy_management:

Files i have:
image

init.py is empty

manifest.json

{
    "domain": "energy_management",
    "name": "Energy Management",
    "documentation": "https://your-documentation-link-here.com",
    "dependencies": [  ],
    "codeowners": [  ],
    "requirements": [  ],
    "version": "0.1.0",
    "config_flow": false,
    "autoload": true,
    "state": ["sensor"],
    "zeroconf": ["_energy-management._tcp.local."],
    "homeassistant": [
      {
        "domain": "sensor",
        "name": "Energy Management",
        "icon": "mdi:flash",
        "device_class": "energy",
        "config_entries": [
          {
            "title": "Energy Management Configuration",
            "description": "Configure the Energy Management component.",
            "ha_version": "0.110.0",
            "requirement": "sensor",
            "entry_class": "config_entries.ConfigEntry",
            "entry_description": "Configuration for the Energy Management component.",
            "entry_title": "Energy Management",
            "entry_id": "config_entry_id",
            "source": "config_entry",
            "connection_class": "local_push"
          }
        ],
        "suggested_area": "Living Room"
      }
    ]
}

sensor.py

import asyncio
from datetime import datetime, timedelta
from homeassistant.helpers.entity import Entity

DOMAIN = "energy_management"

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    async_add_entities([EnergyManagementSensor()])

class EnergyManagementSensor(Entity):
    def __init__(self):
        self._state = None
        self.block_heating_pump = 1  # Renamed to "block_heating_pump"
        self.electricity_hours = 0
        self.electricity_price = []

    async def async_added_to_hass(self):
        await self._update_state()
        await self._schedule_next_update()

    async def _update_state(self):
        nordpool_sensor = self.hass.states.get("sensor.nordpool_kwh_se3_sek_3_10_0")
        tomorrow_valid = nordpool_sensor.attributes.get("tomorrow_valid", False)

        if tomorrow_valid:
            self.electricity_hours = 47
        else:
            self.electricity_hours = 23

        self.electricity_price = nordpool_sensor.attributes.get("raw_today", [])

        if self.electricity_hours == 47:
            self.electricity_price += nordpool_sensor.attributes.get("raw_tomorrow", [])

        # Copy and modify the electricity_price array
        battery_state_plan = [list(row) for row in self.electricity_price]
        for row in battery_state_plan:
            row[1] *= 2  # Multiply the "value" column by 2

        # Store battery_state_plan as an attribute
        self.attributes = {"battery_state_plan": battery_state_plan}

        # Renamed state "additional_state" to "block_heating_pump"
        self.block_heating_pump = 1

        # Check the current hour without minutes and seconds
        current_hour = datetime.now().replace(minute=0, second=0, microsecond=0).strftime("%H:%M:%S")

        # Find and store corresponding "value" for the selected hour
        for row in battery_state_plan:
            if row[0] == current_hour:
                self._state = row[1]
                break

    async def _schedule_next_update(self):
        now = datetime.now()
        next_hour = (now + timedelta(hours=0)).replace(minute=1, second=00, microsecond=0)
        time_until_next_hour = (next_hour - now).total_seconds()
        self.hass.async_create_task(
            asyncio.sleep(time_until_next_hour).then(self._update_and_schedule)
        )

    async def _update_and_schedule(self, _):
        await self._update_state()
        await self._schedule_next_update()
        self.async_write_ha_state()

all looks weird to me :slight_smile: I would look at a basic integration or an existing cookie cutter template.

Many thanks fuatakgun for checking the code!

Clearly ChatGPT still has a lot to learn. I will do it the hard/normal way without shortcuts. I have made a development installation in Docker now and will start with the simple examples in the links you provided

1 Like

Remember that the latest training data for ChatGPT is from September 2021. That is a very long time for the Python development and especially Home Assistant world :wink:

1 Like