Unit conversion B to GB

Hi,

I’m kind of struggling to convert one sensor data from bytes to giga bytes.

I believe the solution is to use “templates”. But I can’t get it to work.

So I have this sensor (or is it an entity?):

sensor.huawei_b818_263_current_month_download

I’ve found the syntax that does the conversion:

"{{ (states('sensor.huawei_b818_263_current_month_download')|filesizeformat(GB)) | round(2) }}"

It works in the developer console, in the template tab.

But I don’t know what to do from there? I can’t use this directly. I have to put it in the configuration file?

I’ve tried adding:

huawei2:
 - platform: template
    sensors:
      huawei_download_month_GB:
        friendly_name: "GB downloaded"
        unit_of_measurement: 'GB'
        value_template: "{{ (states('sensor.huawei_b818_263_current_month_download')|filesizeformat(GB)) | round(2) }}"

In my configuration.yaml (which is unmodified before that).

But i get errors and it won’t load my configuration on reboot.

Try using State-based Template Sensor. Put the below code inside your configuration.yaml-

template:
  - sensor:
      - name: "Huawei Downloaded Month GB"
        unit_of_measurement: "GB"
        state: >-
          {{ (states('sensor.huawei_b818_263_current_month_download') | filesizeformat(GB)) }}

You should then have a new sensor entity called sensor.huawei_downloaded_month_gb

Thanks! It works!

However, I get a bunch of these warnings in my Home Assistant container journal

2021-08-30 13:36:47 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'GB' is undefined when rendering '{{ (states('sensor.huawei_b818_263_current_month_upload') | filesizeformat(GB)) | round(2) }}'

Sorry, I never used filesizeformat(GB). When you paste it in Developer Tools → Template, does it produces your desired result?

It does.

"{{ (states('sensor.huawei_b818_263_current_month_download')|filesizeformat(GB)) | round(2) }}"

Outputs:
“50.9 GB”

With type set as string

When I add it in my lovelace dashboard I get no history. Even though the sensor linked to this template has history. Maybe I should us a different method to convert to GB than retains a type float?

You might want to take a look at this-