core: Melcloud integration- Reports wrong energy value for the total consumption

The problem

For about a week now, since the issue where MelCloud started to impose a rate limiting (see https://github.com/home-assistant/core/issues/109728) there’s been other issues.

First of all, the daily consumption is gone. I’ve searched a bit and it looks like it was a deliberate move to get less calls for the polling. CF https://github.com/home-assistant/core/commit/5521a3986699b8af6dbc34bd422f7b9583b6ab8f. I don’t consider this a big issue, it’s easy enough to recreate with a helper using the total consumption.

Now, what’s more of a problem at the moment, is that since this all started (~ last week), the total consumption appears to be wrong. It’s a lot lower than what it should be. To give an idea, it’s roughly the same weather since last week and you can look at the break down of my consumption in the following picture. The orange bar is the consumption of the heatpump, notice how it’s super low for a week now:

image

Here are some value comparison between cloud data from the MelCloud app and my HA data, in kWh:

Date HA MelCloud Ratio
14/02/24 2.0 14.4 7.20
13/02/24 2.4 14.9 6.20
12/02/24 1.9 11.5 6.05
11/02/24 1.8 13.8 7.66

Looking at the ratio, it look like it’s always between ~6 and ~8 times less on HA than MelCloud.

As the polling period has been extended, if there isn’t a poll made right before midnight, I’m guessing we could have some of the HA value slightly different for the day compared to MelCloud, which might explain that we’re not getting the same ratio. Or it’s totally unrelated, unsure.

While the main feature to manage the heat pump temperature is working again (which is great, thanks for reacting so quickly!), it’s still quite problematic in my case as I was hoping to get good quality stats after buying the heat pump right when winter started to be able to make long term stats difference pre heat pump VS now (not using HA, using Grafana but it gets the data from HA still).

I have looked for similar issues and found this one https://github.com/home-assistant/core/issues/109864 but I think it was wondering about the daily consumption and as stated at the beginning of this issue, it was a deliberate move and it can be fixed easily so this issue is really about fixing the total consumption.

I don’t get to create loads of issue on HA, so I’ll take this one to say a massive thank you for the work you’re doing and I’m quite impressed with the pace at which HA ships new feature. Top 3 of my favourite open source projects for sure.

What version of Home Assistant Core has the issue?

2024.2.1

What was the last working version of Home Assistant Core?

No response

What type of installation are you running?

Home Assistant Container

Integration causing the issue

MelCloud

Link to integration documentation on our website

https://www.home-assistant.io/integrations/melcloud

Diagnostics information

Not sure it’s needed in that case but let me know otherwise

Example YAML snippet

No response

Anything in the logs that might be useful for us?

I'm afraid not

Additional information

No response

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 1
  • Comments: 58 (2 by maintainers)

Most upvoted comments

I stumbled upon the same and it took me a while to figure that out but: when you show the energy report in the MELcloud app you are using a different endpoint. NOT the endpoint ListDevices, which contains the wrong value (God knows why it is there in the first place), but the endpoint EnergyCost/Report.

I finally made it work yesterday, after many attempts - and so far it seems to do the trick. It also looks like it matches what the energy report shows, so…great I guess.

You may want to try it out yourself, code is below. I have added comments, hope it helps.

Here is what my result looks like. I have other derived sensors and utility meters linked to that sensor, so I use it basically as a lifetime meter sensor. image

One comment on the API requests: it seemed a bit random, which header parameters were necessary (I played around and believe that the ones I use are required. Anyway, it works for me so I don’t see the need of changing them for now.


# Step 1: REST API Authentication
#### You will need your MELcloud credentials for the authentication step. 
#### You retrieve a session key (that is stored in a template sensor, see below) that you need in further API requests
rest:
  - method: POST
    resource: https://app.melcloud.com/Mitsubishi.Wifi.Client/Login/ClientLogin
    username: your@e.mail # I use Home Assistant secrets, !secret melcloud_user
    password: yourPassword # I use Home Assistant secrets, !secret melcloud_password
    authentication: basic
    scan_interval: 86400
    timeout: 100
    verify_ssl: true
    headers:
        Accept: application/json, text/javascript, */*; q=0.01
        Origin: https://app.melcloud.com/
        Referer: https://app.melcloud.com/
        X-Requested-With: XMLHttpRequest
        User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
        Sec-Fetch-Mode: cors
        Content-Type: application/json
    payload: '{"Email":"your@e.mail","Password":"yourPassword","Language":"13","AppVersion":"1.18.5.1","Persist":"true","CaptchaResponse":"" }'
    sensor:
      - name: rest_melcloud_auth
        unique_id: rest_melcloud_auth
        value_template: "OK"
        force_update: true
        json_attributes_path: "$..LoginData"
        json_attributes: # actually you only need the context key. rest is optional
          - ContextKey
          - Client
          - Language
          - Country
          - Name
          - Duration
          - Expiry
          - LanguageCode
          - CountryName
# Step 2: Retrieve energy report
#### Here you need the session key from step 1 which is stored in sensor.rest_melcloud_context_key
#### You will also need the device ID of your heat pump/AC. How to find out your device id is described here:
#### https://community.home-assistant.io/t/mitsubishi-melcloud-integration-with-home-assistant/26275/526
  - method: POST
    resource: https://app.melcloud.com/Mitsubishi.Wifi.Client/EnergyCost/Report
    scan_interval: 300 # i had it set to 1 minute first, but you will see it is not necessary to poll that often
    timeout: 100
    verify_ssl: true
    headers:
        X-Requested-With: XMLHttpRequest
        X-MitsContextKey: "{{ states('sensor.rest_melcloud_context_key') }}"
        Accept: application/json, text/javascript, */*; q=0.01
        Origin: https://app.melcloud.com/
        Referer: https://app.melcloud.com/
        User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
        Sec-Fetch-Mode: cors
        Content-Type: application/json
    payload: '{"DeviceId":49650456,"FromDate":"1970-01-01","ToDate":"2099-12-31","UseCurrency":false}'
    sensor:
      - name: rest_melcloud_energyreport
        unique_id: rest_melcloud_energyreport
        value_template: "OK"
        force_update: true
        json_attributes:
          - TotalHeatingConsumed
          - TotalCoolingConsumed
          - TotalAutoConsumed
          - TotalDryConsumed
          - TotalFanConsumed
          - TotalOtherConsumed
          - FromDate
          - ToDate
# The first template sensor retrieves the context key from the Authentication step
# Th second template sensor sums up all the energy totals (heating, cooling, etc). Feel free to modify.
# The result is a lifetime consumption meter of your device, which you can use as it pleases you
template:
  - sensor:
      - name: "REST MELCloud context key"
        unique_id: "rest_melcloud_context_key"
        availability: >
          {{ (states("sensor.rest_melcloud_auth") not in ["unknown", "unavailable"]) and (state_attr('sensor.rest_melcloud_auth', 'ContextKey') != None) }}
        state: >
          {{ state_attr('sensor.rest_melcloud_auth', 'ContextKey') }}
      - name: "MELCloud Energy Consumption Total"
        unique_id: "melcloud_energy_consumption_total"
        unit_of_measurement: kWh
        device_class: energy
        state_class: total_increasing
        availability: >
          {{ (states("sensor.rest_melcloud_energyreport") not in ["unknown", "unavailable"]) and (state_attr('sensor.rest_melcloud_energyreport', 'TotalHeatingConsumed') != None) }}
        state: >
          {{ (state_attr('sensor.rest_melcloud_energyreport', 'TotalHeatingConsumed') + state_attr('sensor.rest_melcloud_energyreport', 'TotalCoolingConsumed') + state_attr('sensor.rest_melcloud_energyreport', 'TotalAutoConsumed') + state_attr('sensor.rest_melcloud_energyreport', 'TotalDryConsumed') + state_attr('sensor.rest_melcloud_energyreport', 'TotalFanConsumed') + state_attr('sensor.rest_melcloud_energyreport', 'TotalOtherConsumed'))|float }}
  

I am also wondering, why nothing happens within this issue.

That’s the endpoint I’m speaking of. Yesterday my entire house (running everything on electricity) consumed 28kwh, the report on that endpoint (and same result shown in the melcloud app) for yesterday was giving 33kwh only for the heatpump 😅

(small update on my side, the melcloud guess at energy consumption is really way off, it exceeds for the 1 heat pump everything that is consumed in my house during the entire day. Messing up the energy dashboard so I just stopped using all this. I guess there’s no way around a proper electric module to see how much energy is really used as estimations are way off).

@le-clu Thank you so much!

Minor thing though which I wasn’t quite able to figure out. How would I reference the !secret melcloud_user and !secret melcloud_pass in the payload?

payload: '{"Email":"your@e.mail","Password":"yourPassword","Language":"13","AppVersion":"1.18.5.1","Persist":"true","CaptchaResponse":"" }'

Hi @mlauhalu Haven’t figured that out either (or let’s call it laziness). So right now, my payload string still has the password in plain text, which is not beautiful. I read somewhere that you might need to create the entire string as a secret, but haven’t tried that yet.

Does this mean the meldcloud API offers the correct value, but it gets transfered wrong through the pymeldcloud integration?

I haven’t dug this deep… But my guess is that melcloud api returns a value, and the conversion ran by the python script is wrong. I’d guess that maybe they changed upstream the unit of what’s being sent… But I haven’t checked.

image

Lol, you took this picture from a post I made 3 days ago, and just like me initially I think you didn’t notice that the date was 2022 😄

Ok I dug into this a little bit…

I had a look at the repo HA is using: https://github.com/vilppuvuorinen/pymelcloud

I then created 3 files:

requirements.txt (as per the one defined in HA)

aiohttp
pymelcloud==2.5.9

main.py

import aiohttp
import asyncio
import pymelcloud

async def main():

    async with aiohttp.ClientSession() as session:
        # call the login method with the session
        token = await pymelcloud.login("EMAIL_HERE", "PASSWORD_HERE", session=session)

        # lookup the device
        devices = await pymelcloud.get_devices(token, session=session)
        print(devices)
        device = devices[pymelcloud.DEVICE_TYPE_ATA][0]
        print(device)

        # perform logic on the device
        await device.update()

        print(device.total_energy_consumed)
        await session.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Dockerfile

FROM python:3.10

WORKDIR /usr/src/app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD [ "python", "./main.py" ]

And then ran

docker build -t test-melcloud-python . && docker run --rm test-melcloud-python:latest

The call to the API gives me… 🥁 The wrong answer 😞 …

So it looks like HA is doing the right thing but most likely the API changed upstream and this isn’t computing the correct value. As per my previous message, I guess this changed.

The repo has been archived 10 days ago… So we’re unlikely to get a fix unless there’s a fork made by someone I guess. I don’t know what HA does in those circumstances but maybe instead of importing the lib it could have the code defined in HA core directly? Or make an HA fork so that it can be owned by the community? Because right now there’s no way to make a fix upstream, can’t even create an issue to ask if anyone has done a fork because the repo is readonly…

Mine reports a too low value. It feels like it should be 10 times higher. They are consuming 1000-2000 W per hour, according to other measurments I have on them, and still reports using like 100-200w. Really strange.