Need help with MQTT device

Hi

I’m relatively new to HA and MQTT and I’m hoping someone can point me in the right direction to help me solve an issue I’m getting with mqtt based sensor. I’m using an ESP32 device with ESPHome MQTT to count the pulses on a power meter and sending total energy imported messages. In that location I’m also running a RPI with Mosquitto that is connected to HiveMq cloud. HA at home is running the MQTT integration connected to HiveMq.

I’m getting occasional data glitches that causes my sensor template to pick up what looks like an earlier mqtt message. When the glitches occur, it matches the the data point just prior to the previous glitch as shown in the charts below.

Here are code snippets, please let me know if I’m missing anything.

ESPHome device:


mqtt:
  topic_prefix: power-meter
  broker: 192.168.1.233
  username: ""
  password: ""
  discovery: true
  birth_message:
    topic: power-meter/status
    payload: online
  will_message:
    topic: power-meter/status
    payload: offline

sensor:
  - platform: pulse_counter
    pin: 12
    unit_of_measurement: 'kW'
    name: 'Power Import'
    accuracy_decimals: 3
    filters:
      - multiply: 0.06  # (60s/1000 pulses per kWh)

    total:
      unit_of_measurement: 'kWh'
      name: 'Energy Import'
      accuracy_decimals: 3
      filters:
        - multiply: 0.001  # (1/1000 pulses per kWh)

HA yaml config template:

mqtt:
  sensor:
    - name: "Grid Import Energy"
      state_topic: "power-meter/sensor/energy_import/state"
      unique_id: cb658877-f7f5-4061-914a-55f97b7ad7e9
      state_class: total
      device_class: energy
      unit_of_measurement: "kWh"

I would appreciate any clues to what might be causing the glitches and why it’s picking up that specific value when it happens.

Many thanks,

Bruno

Update: I have another local MQTT broker for presence sensing (different location, but also connected to HiveMq) and when it reboots it triggers the issue I’m seeing. Didn’t occur to me earlier that this could be involved.

I’ll do more research to understand what’s happening and how to fix this, but presumably the broker fires off retained messages when it gets back online. (Also need to workout why the broker doesn’t stay online, but that’s another issue)

Cheers,

Bruno