Repository: zigpy/zha-device-handlers

Issue:
[BUG] Aqara plug (lumi.plug.maeu01) generates errors post-2022.2
**Describe the bug**
I use this plug with HA 2022.2.3, where it's been updated to use the quirk for lumi.plug.mmeu01 after [this pull](https://github.com/zigpy/zha-device-handlers/pull/1252/commits).

There are errors popping up in the log after this update.

```
Logger: homeassistant.util.logging
Source: util/logging.py:105
First occurred: 4:34:56 PM (16 occurrences)
Last logged: 4:55:26 PM

Exception in async_state_changed when dispatching 'LUMI lumi.plug.maeu01_54:ef:44:10:00:0e:52:9d_available_entity': () Traceback (most recent call last): 
 File  "/usr/src/homeassistant/homeassistant/components/zha/entity.py", line 107, in async_state_changed self.async_write_ha_state() 
 File  "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 530, in async_write_ha_state self._async_write_ha_state() 
 File  "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 563, in _async_write_ha_state state = self._stringify_state() 
 File  "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 536, in _stringify_state if (state := self.state) is None: 
 File  "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 371, in state value = self.native_value 
 File  "/usr/src/homeassistant/homeassistant/components/zha/sensor.py", line 175, in native_value return self.formatter(raw_state) 
 File  "/usr/src/homeassistant/homeassistant/components/zha/sensor.py", line 472, in formatter return self._channel.summa_formatter(value) 
 File  "/usr/src/homeassistant/homeassistant/components/zha/core/channels/smartenergy.py", line 196, in _formatter_function return self._summa_format.format(value).lstrip() AttributeError: 'NoneType' object has no attribute 'format'
```

**To Reproduce**
Steps to reproduce the behavior: unknown

**Additional context**
```
{
  "node_descriptor": "NodeDescriptor(logical_type=<LogicalType.Router: 1>, complex_descriptor_available=0, user_descriptor_available=0, reserved=0, aps_flags=0, frequency_band=<FrequencyBand.Freq2400MHz: 8>, mac_capability_flags=<MACCapabilityFlags.AllocateAddress|RxOnWhenIdle|MainsPowered|FullFunctionDevice: 142>, manufacturer_code=4447, maximum_buffer_size=127, maximum_incoming_transfer_size=100, server_mask=11264, maximum_outgoing_transfer_size=100, descriptor_capability_field=<DescriptorCapability.NONE: 0>, *allocate_address=True, *is_alternate_pan_coordinator=False, *is_coordinator=False, *is_end_device=False, *is_full_function_device=True, *is_mains_powered=True, *is_receiver_on_when_idle=True, *is_router=True, *is_security_capable=False)",
  "endpoints": {
    "1": {
      "profile_id": 260,
      "device_type": "0x0051",
      "in_clusters": [
        "0x0000",
        "0x0002",
        "0x0003",
        "0x0004",
        "0x0005",
        "0x0006",
        "0x0009",
        "0x0702",
        "0x0b04"
      ],
      "out_clusters": [
        "0x000a",
        "0x0019"
      ]
    },
    "21": {
      "profile_id": 260,
      "device_type": "0x0009",
      "in_clusters": [
        "0x000c"
      ],
      "out_clusters": [
        "0x0004",
        "0x000c"
      ]
    },
    "242": {
      "profile_id": 41440,
      "device_type": "0x0061",
      "in_clusters": [],
      "out_clusters": [
        "0x0021"
      ]
    }
  },
  "manufacturer": "LUMI",
  "model": "lumi.plug.maeu01",
  "class": "zhaquirks.xiaomi.aqara.plug_mmeu01.Plug"
}
```



Discussion:
I also have problems with this device on version 2022.2.6

```javascript{
  "node_descriptor": "NodeDescriptor(logical_type=<LogicalType.Router: 1>, complex_descriptor_available=0, user_descriptor_available=0, reserved=0, aps_flags=0, frequency_band=<FrequencyBand.Freq2400MHz: 8>, mac_capability_flags=<MACCapabilityFlags.AllocateAddress|RxOnWhenIdle|MainsPowered|FullFunctionDevice: 142>, manufacturer_code=4447, maximum_buffer_size=127, maximum_incoming_transfer_size=100, server_mask=11264, maximum_outgoing_transfer_size=100, descriptor_capability_field=<DescriptorCapability.NONE: 0>, *allocate_address=True, *is_alternate_pan_coordinator=False, *is_coordinator=False, *is_end_device=False, *is_full_function_device=True, *is_mains_powered=True, *is_receiver_on_when_idle=True, *is_router=True, *is_security_capable=False)",
  "endpoints": {
    "1": {
      "profile_id": 260,
      "device_type": "0x0051",
      "in_clusters": [
        "0x0000",
        "0x0002",
        "0x0003",
        "0x0004",
        "0x0005",
        "0x0006",
        "0x0009",
        "0x0702",
        "0x0b04"
      ],
      "out_clusters": [
        "0x000a",
        "0x0019"
      ]
    },
    "21": {
      "profile_id": 260,
      "device_type": "0x0009",
      "in_clusters": [
        "0x000c"
      ],
      "out_clusters": [
        "0x0004",
        "0x000c"
      ]
    },
    "242": {
      "profile_id": 41440,
      "device_type": "0x0061",
      "in_clusters": [],
      "out_clusters": [
        "0x0021"
      ]
    }
  },
  "manufacturer": "LUMI",
  "model": "lumi.plug.maeu01",
  "class": "zhaquirks.xiaomi.aqara.plug_mmeu01.Plug"
}`
Same here! I did a post on Home Assistant community to track my research around it 
https://community.home-assistant.io/t/aqara-smart-plug-reporting-energy-unavailable/395392
I also have issues with maeu01 plug after this pull. Power reading is unavailable and Energy is reading but not updating unless I do a manual read of the cluster, then it is updated in HA.
Since it is not updating the entire device goes unavailable every 2 hours (as per setting in ZHA for mains powered devices).

The thing is that my device worked perfectly before this pull and now re-pairing it makes no difference.

Admittedly I'm not great at navigating Github, is it possible to find which quirk this device used before the pull? No one at all or a different quirk? If there was another quirk for it before I could try and add the old one as a custom quirk and see if the device behaves as it should.
@EagleStClair, I'm in the same boat. I've [posted](https://community.home-assistant.io/t/aqara-plug-sp-euc01-lumi-plug-maeu01-not-updating/393110) in the HA forums, but the only other people replying are the ones also experiencing the same or similar issues. I've got not idea how to get the people with the proper knowledge to actually take a look at it. 

I'm struggling with the same questions about the quirks and also can't seem to find the exact files to use to for custom quirks. I wish the documentation was a bit better.
There are many more having this issue but keep only a watching eye on github. Me personally I jumped from deconz to zha and after being happy for 2 days all went down the drain because power and energy measurements are gone…
Not sure if it's a solution for everyone, but I switched to using Zigbee2mqtt instead of ZHA and now my device works perfectly! 
The error is because the `_summa_format` attribute for the smart energy metering cluster is `None`. This cluster is not replaced by the quirk from what I can tell so I am unsure how this was working previously. I will try to look at this closer later tonight. 
@dmulcahey it was NOT working previously. Prior to this upgrade, the maeu01 plug only had on/off functionality (at least in my tests), but did not produce any errors in the log. It had NO quirk applied, as the device signature did not match anything.

It's true that Aqara devices take a lot of attempts to be paired properly (i.e. by exposing all endpoints/clusters) and it might be that I didn't go through enough iterations to actually have all endpoints exposed, but before HA 2022.2, I've never had power monitoring, energy consumption etc., not even as non-functioning entities.
@dmulcahey and @tetele, on my side I have 2 smart plugs, 1 add to home assistant 1 months ago and working perfectly and 1 added 2 weeks ago reporting only on/off.

I dive deep on the issue (as far I can go) and you the error seems to be linked the `_summa_format` but both report the same value for Metering cluster (0x0702) attribute summa_formatting (0x0303).

So basically everything seems to work when a call the cluster directly but Home Assistant couldn't get those metrics. Maybe it's something a bit fragile at the onboarding the HA must be more resilant like putting a default value for `_summa_format`.
Can you read the attribute from the manage cluster screen and post a screenshot? Then if a value is returned for it, restart HA and tell me what happens with the non working device
Desk Power is the working one and Workshop Power have unavailable power metrics

<img width="1180" alt="Screenshot 2022-02-28 at 17 01 40" src="https://user-images.githubusercontent.com/236866/156016044-71ac47dc-14b7-492d-a42f-2982e88ba062.png">
<img width="1120" alt="Screenshot 2022-02-28 at 17 00 44" src="https://user-images.githubusercontent.com/236866/156016059-4a81a078-25f5-4363-9b02-1a33e95ba654.png">
I have the exact same situation as @mazerte. I've also restarted HA and looked in the logs. I found these errors related to ZHA:

(my plugs have the following NWKs - 0xfcff for the one that's reporting energy consumption and 0x08bf for the one that doesn't)

```
Logger: homeassistant.components.zha.core.channels.base
Source: components/zha/core/channels/base.py:428
Integration: Zigbee Home Automation ([documentation](https://www.home-assistant.io/integrations/zha), [issues](https://github.com/home-assistant/home-assistant/issues?q=is%3Aissue+is%3Aopen+label%3A%22integration%3A+zha%22))
First occurred: 18:29:44 (5 occurrences)
Last logged: 18:29:46

[0x930F:1:0x0006]: async_initialize: all attempts have failed: [DeliveryError('[0x930f:1:0x0006]: Message send failure'), DeliveryError('[0x930f:1:0x0006]: Message send failure'), DeliveryError('[0x930f:1:0x0006]: Message send failure'), DeliveryError('[0x930f:1:0x0006]: Message send failure')]
[0x930F:1:0x0002]: async_initialize: all attempts have failed: [DeliveryError('[0x930f:1:0x0002]: Message send failure'), DeliveryError('[0x930f:1:0x0002]: Message send failure'), DeliveryError('[0x930f:1:0x0002]: Message send failure'), DeliveryError('[0x930f:1:0x0002]: Message send failure')]
[0x69C8:1:0x0002]: async_initialize: all attempts have failed: [DeliveryError('[0x69c8:1:0x0002]: Message send failure'), DeliveryError('[0x69c8:1:0x0002]: Message send failure'), DeliveryError('[0x69c8:1:0x0002]: Message send failure'), DeliveryError('[0x69c8:1:0x0002]: Message send failure')]
[0x69C8:2:0x0006]: async_initialize: all attempts have failed: [DeliveryError('[0x69c8:2:0x0006]: Message send failure'), DeliveryError('[0x69c8:2:0x0006]: Message send failure'), DeliveryError('[0x69c8:2:0x0006]: Message send failure'), DeliveryError('[0x69c8:2:0x0006]: Message send failure')]
[0x69C8:1:0x0006]: async_initialize: all attempts have failed: [DeliveryError('[0x69c8:1:0x0006]: Message send failure'), DeliveryError('[0x69c8:1:0x0006]: Message send failure'), DeliveryError('[0x69c8:1:0x0006]: Message send failure'), DeliveryError('[0x69c8:1:0x0006]: Message send failure')]
```

```
Logger: homeassistant.components.sensor
Source: components/zha/core/channels/smartenergy.py:196
Integration: Sensor ([documentation](https://www.home-assistant.io/integrations/sensor), [issues](https://github.com/home-assistant/home-assistant/issues?q=is%3Aissue+is%3Aopen+label%3A%22integration%3A+sensor%22))
First occurred: 18:29:46 (1 occurrences)
Last logged: 18:29:46

Error adding entities for domain sensor with platform zha
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 382, in async_add_entities
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 614, in _async_add_entity
    await entity.add_to_platform_finish()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 782, in add_to_platform_finish
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 539, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 572, in _async_write_ha_state
    state = self._stringify_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 545, in _stringify_state
    if (state := self.state) is None:
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 371, in state
    value = self.native_value
  File "/usr/src/homeassistant/homeassistant/components/zha/sensor.py", line 174, in native_value
    return self.formatter(raw_state)
  File "/usr/src/homeassistant/homeassistant/components/zha/sensor.py", line 471, in formatter
    return self._channel.summa_formatter(value)
  File "/usr/src/homeassistant/homeassistant/components/zha/core/channels/smartenergy.py", line 196, in _formatter_function
    return self._summa_format.format(value).lstrip()
AttributeError: 'NoneType' object has no attribute 'format'

```

```
Logger: homeassistant
Source: components/zha/core/channels/smartenergy.py:196
First occurred: 18:29:46 (1 occurrences)
Last logged: 18:29:46

Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 382, in async_add_entities
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 614, in _async_add_entity
    await entity.add_to_platform_finish()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 782, in add_to_platform_finish
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 539, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 572, in _async_write_ha_state
    state = self._stringify_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 545, in _stringify_state
    if (state := self.state) is None:
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 371, in state
    value = self.native_value
  File "/usr/src/homeassistant/homeassistant/components/zha/sensor.py", line 174, in native_value
    return self.formatter(raw_state)
  File "/usr/src/homeassistant/homeassistant/components/zha/sensor.py", line 471, in formatter
    return self._channel.summa_formatter(value)
  File "/usr/src/homeassistant/homeassistant/components/zha/core/channels/smartenergy.py", line 196, in _formatter_function
    return self._summa_format.format(value).lstrip()
AttributeError: 'NoneType' object has no attribute 'format'
```

After the restart, the summa_format attribute (0x0702 > 0x0303) can be read from the device not reporting energy and its value is `bitmap8.32|2|1`
After reading that value can you restart again please?
Yes, but what info do you need after the second restart?
Once the attribute is read and cached that error should be gone after restarting and I’m wondering if the entities will be back
So, I read the `summa_format` attribute on the device that's not reporting energy consumption, then restarted HA.

I can't find any ZHA-related log entries after restart (except for something regarding a device that ran out of battery, but that's expected).

The plug still doesn't report the energy.

![2022-03-01_13-36-18](https://user-images.githubusercontent.com/920098/156162458-bd4a4717-7673-46fc-b351-49813f2b0906.png)

Note that `summation_delivered`, `apparent_power`, `rms_current` and `rms_voltage` are `unavailable`, `smartenergy_metering` is `unknown`.
The unknown entity was previously unavailable right? Can you turn in the washing machine so it draws power or can you plug something else into the plug that uses power for a bit? We can address the other entities next but I want to know if that unknown flips to a value after the attribute is reported 
The unknown entity has been unknown for a while, IIRC.

I've plugged in an electric heater and nothing happens after a couple of minutes. At 1kW, it should start moving the needle pretty quickly, I guess.

![2022-03-01_14-09-37](https://user-images.githubusercontent.com/920098/156166981-02818ac5-23f0-4f15-b526-835b6eb8f1d9.png)
Here's something interesting about the other plug (the one that, apparently, DOES report energy consumption): I've plugged in the same heater for more than 1/10 of an hour, and the energy consumption (measured in kWh with single decimal precision) has not increased with 0.1kWh, as expected.

![2022-03-01_14-26-57](https://user-images.githubusercontent.com/920098/156169177-55f41175-1df4-416b-a56b-a47f886d6264.png)

More over, here's the log

```
Logger: homeassistant.util.logging
Source: util/logging.py:105
First occurred: 13:32:19 (54 occurrences)
Last logged: 14:25:19

Exception in async_state_changed when dispatching 'LUMI lumi.plug.maeu01_54:ef:44:10:00:0e:52:9d_available_entity': () Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/components/zha/entity.py", line 107, in async_state_changed self.async_write_ha_state() File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 539, in async_write_ha_state self._async_write_ha_state() File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 572, in _async_write_ha_state state = self._stringify_state() File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 545, in _stringify_state if (state := self.state) is None: File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 371, in state value = self.native_value File "/usr/src/homeassistant/homeassistant/components/zha/sensor.py", line 174, in native_value return self.formatter(raw_state) File "/usr/src/homeassistant/homeassistant/components/zha/sensor.py", line 471, in formatter return self._channel.summa_formatter(value) File "/usr/src/homeassistant/homeassistant/components/zha/core/channels/smartenergy.py", line 196, in _formatter_function return self._summa_format.format(value).lstrip() AttributeError: 'NoneType' object has no attribute 'format'
```

which is, basically, the same error as in the originally reported issue.
> 

That is what I'm seeing as well. Does it update if you get the zigbee attribute manually?
Mine does if I read current_summ_delivered (id: 0x0000):
![image](https://user-images.githubusercontent.com/57722801/156368225-8648edea-8ada-4d2c-afe0-080ef3339d69.png)

Then the corresponding sensor is updated as well:
![image](https://user-images.githubusercontent.com/57722801/156368280-d7ae49b5-d44b-497d-8a05-c0258e2d2c61.png)

But HA never updates the sensors without me manually reading the attribute.

That's probably why ZHA consider my plug unavailable every 2 hours - no values are read/reported so 7200 sec is the limit for considering a mains powered device unavailable.
![image](https://user-images.githubusercontent.com/57722801/156368542-56bf32eb-4b08-41e5-9dfd-78cd9a603d9f.png)

For me it just reports 0 even if I query the attribute (in the Manage Clusters screen as well as in the HA interface).
I have similar problems. All sensors on the SP-EUC01 (lumi.plug.maeu01) show "unknown" as the value and turn completely unavailable after a reboot. The On/Off toggle function works just fine, but recently ZHA drops the entire device and I have to re-pair it. 😞
I have the same here. All the states show as unknown. Getting the attribute manually gives me a value.
![image](https://user-images.githubusercontent.com/4869375/156932413-a0f455de-7f25-441f-9eea-4db94f41ddfe.png)




> I have the same here. All the states show as unknown. Getting the attribute manually gives me a value.

This is precisely what I'm seeing as well and a short time after getting the value manually (somewhere around 1h), ZHA just drops/disconnects from the device completely. But then again, if I don't get the value manually, ZHA still disconnects eventually for no good reason. 🤷‍♂️

And also, the values are not shown correctly. For example, I tried to get the temperature manually. The device initially reported it as 22°C, but as soon as I try to save the attribute it is shown as 0.2°C.
At the office we also have one of these plugs (the reason that I bought mine) that does work.
![image](https://user-images.githubusercontent.com/4869375/157032186-6e9ea239-d096-4a9a-98a4-96f88f768c25.png)

> At the office we also have one of these plugs (the reason that I bought mine) that does work.

Interesting. What HA core version is running at your workplace? 
My home setup:
## System Health

version | core-2022.3.1
-- | --
installation_type | Home Assistant OS
dev | false
hassio | true
docker | true
user | root
virtualenv | false
python_version | 3.9.9
os_name | Linux
os_version | 5.10.92-v7
arch | armv7l
timezone | Europe/Amsterdam

<details><summary>Home Assistant Community Store</summary>

GitHub API | ok
-- | --
Github API Calls Remaining | 5000
Installed Version | 1.22.0
Stage | running
Available Repositories | 1005
Downloaded Repositories | 3

</details>

<details><summary>Home Assistant Cloud</summary>

logged_in | true
-- | --
subscription_expiration | March 17, 2022, 1:00 AM
relayer_connected | true
remote_enabled | true
remote_connected | true
alexa_enabled | false
google_enabled | false
remote_server | eu-west-2-3.ui.nabu.casa
can_reach_cert_server | ok
can_reach_cloud_auth | ok
can_reach_cloud | ok

</details>

<details><summary>Home Assistant Supervisor</summary>

host_os | Home Assistant OS 7.4
-- | --
update_channel | stable
supervisor_version | supervisor-2022.01.1
docker_version | 20.10.9
disk_total | 13.9 GB
disk_used | 8.7 GB
healthy | true
supported | true
board | rpi3
supervisor_api | ok
version_api | ok
installed_addons | SSH & Web Terminal (10.0.2), Backup Hassio to Google Drive (1.7.10), File editor (5.3.3), AdGuard Home (4.4.5), Nextcloud Backup (0.16.8)

</details>

<details><summary>Lovelace</summary>

dashboards | 1
-- | --
resources | 1
views | 2
mode | storage

</details>

<details><summary>Spotify</summary>

api_endpoint_reachable | ok
-- | --

</details>

At the office:
(But we have had it working on different versions as well at the office.)
## System Health

version | core-2022.3.2
-- | --
installation_type | Home Assistant OS
dev | false
hassio | true
docker | true
user | root
virtualenv | false
python_version | 3.9.9
os_name | Linux
os_version | 5.10.92-v8
arch | aarch64
timezone | Europe/Amsterdam

<details><summary>Home Assistant Community Store</summary>

GitHub API | ok
-- | --
GitHub Content | ok
GitHub Web | ok
GitHub API Calls Remaining | 5000
Installed Version | 1.23.0
Stage | running
Available Repositories | 1004
Downloaded Repositories | 4

</details>

<details><summary>Home Assistant Cloud</summary>

logged_in | false
-- | --
can_reach_cert_server | ok
can_reach_cloud_auth | ok
can_reach_cloud | ok

</details>

<details><summary>Home Assistant Supervisor</summary>

host_os | Home Assistant OS 7.4
-- | --
update_channel | stable
supervisor_version | supervisor-2022.01.1
docker_version | 20.10.9
disk_total | 13.8 GB
disk_used | 4.4 GB
healthy | true
supported | true
board | rpi4-64
supervisor_api | ok
version_api | ok
installed_addons | Terminal & SSH (9.3.0), File editor (5.3.3)

</details>

<details><summary>Lovelace</summary>

dashboards | 1
-- | --
resources | 2
views | 3
mode | storage

</details>

Hmmm... what Zigbee Gateways are being used (both at home and at your workplace)? I'm using a ConBee II. 
Both are conbee 2 sticks
Home:
![image](https://user-images.githubusercontent.com/4869375/157036164-c1464f18-4efb-46d2-90f4-31c9e98c1c48.png)
Office:
![image](https://user-images.githubusercontent.com/4869375/157036364-08ce6daa-04bc-49e3-98f7-1f4978c23d7b.png)

But it seems like it sees it differently. This is also what I see in the device filter in Office HA:
![image](https://user-images.githubusercontent.com/4869375/157036794-0257ed8a-b0fc-4ea4-8231-018747b023fb.png)

Yeah, I'm not sure what to make of this. It seems completely random how the device is being recognized and what sensors are functioning. I'm unfortunately not skilled enough to make any further assessment. But it's good to have all the above posted data. I'm going to add my own tonight after work. Thank you @vinhui for all the info. 
For the maeu01 models: I am fairly certain I know what is wrong. is anyone willing to try to modify the quirk locally? if so, remove this line: https://github.com/zigpy/zha-device-handlers/blob/b0bbbfb6b1f267b7d87d833b1ba5a5b0b127a9a1/zhaquirks/xiaomi/aqara/plug_mmeu01.py#L93, then save the file and restart HA. After HA is back up, reconfigure the device via the reconfigure button on the device card. 

z2m binds the clusters on these: https://github.com/Koenkk/zigbee-herdsman-converters/blob/66bfcdc9405abebe70906b279e96f12de73f26a7/devices/xiaomi.js#L1048
That seems to have worked somewhat, but I'm not getting the 'power usage at this moment' entity. In contrast, the device seems to report a temperature but I'n not sure if that is correct. 
![image](https://user-images.githubusercontent.com/4869375/157098283-6ded5846-3047-44ea-ae42-ff0fd8c83a45.png)

These are some of the details from the reconfigure device output:
![image](https://user-images.githubusercontent.com/4869375/157098570-731c910f-058d-4b8d-9967-a11664344630.png)

If this help, I've observed similar issues with three plugs  "lumi.plug.maeu01". 

I'm running Home Assistant using docker on a Raspberry 3B+
Installation using only a SD card
Zigbee interface: dresden elektronik USB stick ConBee II
Mapped using  /dev/ttyACM0:/dev/ttyACM0
Config folder mapped outside the container, the same  configuration folder is used for all the tests described below.

1/ using HA 2022.3.1: when pairing a socket, I get one control, six sensors and two entries for diagnostic.  All sensors are 'unknown', only the control to switch the socket on/off and the diagnostic 'identify' works (the led on the socket is flashing when "press" is pressed) Same behaviour for all three sockets. Stopped the container.  

2/ using  HA 2022.2.9, remove the sockets, added them again. Same issue as above

3/ using  HA 2021.12.10, remove the sockets, added them again: working. I only have  one control and two sensors (current power and total power)

4/ stopped 2021.12.10 and restarted 2022.3.1. The socket still seems to properly update the two sensors. I get power consumption when the socket is on and the value seems correct. I tried by switching on and off the socket. Got two messages in the log (see below)

I removed and paired again one socket. Same issues as described under (1) 

Hope this helps. 

Log file attached

Logger: homeassistant.components.websocket_api.http.connection
Source: components/websocket_api/connection.py:96 
Integration: Home Assistant WebSocket API (documentation, issues)
First occurred: 19:31:32 (2 occurrences) 
Last logged: 19:31:32

[1871751104] Received invalid command: zha/device

2022-03-07 18:31:32 ERROR (MainThread) [homeassistant.components.websocket_api.http.connection] [1871751104] Received invalid command: zha/device
2022-03-07 18:31:32 ERROR (MainThread) [homeassistant.components.websocket_api.http.connection] [1871751104] Received invalid command: zha/device


[logfile.txt](https://github.com/zigpy/zha-device-handlers/files/8200097/logfile.txt)


> That seems to have worked somewhat, but I'm not getting the 'power usage at this moment' entity. In contrast, the device seems to report a temperature but I'n not sure if that is correct. ![image](https://user-images.githubusercontent.com/4869375/157098283-6ded5846-3047-44ea-ae42-ff0fd8c83a45.png)
> 
> These are some of the details from the reconfigure device output: ![image](https://user-images.githubusercontent.com/4869375/157098570-731c910f-058d-4b8d-9967-a11664344630.png)

Can you try 2 things? 1) restart again and see if all entities show up. 2) if not: remove the device, wait about a minute. Restart HA and join it again. 

I do not expect temp to work correctly without additional work. From the herdsman link above it appears they are polling the device for it and we are not. 
That doesn't seem to change anything.
> For the maeu01 models: I am fairly certain I know what is wrong. is anyone willing to try to modify the quirk locally? if so, remove this line:
> 
> https://github.com/zigpy/zha-device-handlers/blob/b0bbbfb6b1f267b7d87d833b1ba5a5b0b127a9a1/zhaquirks/xiaomi/aqara/plug_mmeu01.py#L93
> 
> , then save the file and restart HA. After HA is back up, reconfigure the device via the reconfigure button on the device card.

My HA setup is a HA Blue. How do I access this file? With a Terminal addon?
@Lampyridae1984 https://developers.home-assistant.io/docs/operating-system/debugging/

@dmulcahey it didn't do anything for me, apparently.

I have a feeling that it depends a lot on how the plug was initially paired (i.e. what data it exchanged with the coordinator). I say that because neither of my plugs had the signature that the quirk demanded initially, but after multiple pairing attempts, it sort of worked.

I would like to debug this in more detail, but I don't know exactly how to set things up. @dmulcahey are there any docs/tutorial for setting up and debugging zigpy? I have a bit of experience in software development and debugging, but not with Python. However, I'm willing to give it a go, as long as I can learn a bit about how to set things up.
I run homeassistant core in docker on a intel nuc6i3 (os:ubuntu) + ZHA + conbee2. 

One of my four aqara plugs became unavailable and stopped reporting watts / kwh after I updated to core-2022.3.3
![image](https://user-images.githubusercontent.com/50098214/157344549-085fcb7e-c579-4f8c-bad8-ad914f9f9760.png)
(but this screenshot I had went back to 2021.11.0 to see if it would solve, it did not help) 

I think resetting the plug to factory default solved the problem for me, I tried a bunch of things so not 100% (I'm a bit of a noob) but basically: installed deconz, added the plug as a light in phoscon app, in deconz reset the plug to factory defaults (under basic cluster). Then remove it from deconz and add in homeassistant again:
![image](https://user-images.githubusercontent.com/50098214/157343586-3c7a1d85-2fe3-4569-aea5-6e5e1a979f19.png)

After updating to  the plug got a new sensor "electrical_measurement_apparent_power" which I don't know what it is, also before version 2022.3.3 I never saw "device_temperature" sensor either.
@dmulcahey Hi David,  I like to pass you a feedback, ..strictly followed your suggestion (removed line 93), but without any relevant result, no sensors found.
![image](https://user-images.githubusercontent.com/59331592/157416608-c20cb1cf-0611-438a-ad31-c0eedfc58986.png)

..even with 
93     SKIP_CONFIGURATION: False,
same result.

Important! In this and all the subsequent pairings attempts the zhaquirks.xiaomi.aqara.plug_mmeu01.Plug has not been detected neither base release or modified ones.
@dmulcahey by updating the aqara(xiaomi) firmware to [09.2020 ](https://github.com/Koenkk/zigbee-OTA/blob/master/images/Xiaomi/OTA_lumi.plug.maeu01_V32_20200922_C11F8A.20200924102946.ota) I got a small improvement:
quirks is detected, but after the first HAcore 2022.3.3 reboot few sensors, some of them not used by the plug (see rms_voltage and rms_current...), are now on unknow status.
![image](https://user-images.githubusercontent.com/59331592/157873714-bae1caca-75b1-404f-9db8-a447e7243b2b.png)

@Stefano0042 how did you update the firmware? Do you need an Aqara hub to do so?
@tetele Hi Tudor if you do not have a Deconz/Conbee II  instance running somewhere, you can go for the official [zigpy  OTA update procedure](https://github.com/zigpy/zigpy/wiki/OTA-Device-Firmware-Updates#enabling-ota-updates).
> you can go for the official [zigpy OTA update procedure](https://github.com/zigpy/zigpy/wiki/OTA-Device-Firmware-Updates#enabling-ota-updates).

Thanks, @Stefano0042! My bad, the question was more related to where you got the firmware from, rather than how to upload it to the plug :D I take Deconz takes care of that automatically, and I don't have it.
Hi, normally you can have a chance in Koenkk repository [(just click here) 09.2020](https://github.com/Koenkk/zigbee-OTA/blob/master/images/Xiaomi/OTA_lumi.plug.maeu01_V32_20200922_C11F8A.20200924102946.ota)
..here is HAcore 2021.3.4 plug_mmeu01.py ver., was only meant for mmeu01 firmware.

```
"""Xiaomi lumi.plug.mmeu01 plug."""
import logging

from zigpy.profiles import zha
from zigpy.zcl.clusters.general import (
    Alarms,
    AnalogInput,
    Basic,
    DeviceTemperature,
    GreenPowerProxy,
    Groups,
    Identify,
    OnOff,
    Ota,
    Scenes,
    Time,
)
from zigpy.zcl.clusters.homeautomation import ElectricalMeasurement
from zigpy.zcl.clusters.smartenergy import Metering

from .. import (
    LUMI,
    AnalogInputCluster,
    BasicCluster,
    ElectricalMeasurementCluster,
    XiaomiCustomDevice,
)
from ... import Bus
from ... import (
    DEVICE_TYPE,
    ENDPOINTS,
    INPUT_CLUSTERS,
    MODELS_INFO,
    OUTPUT_CLUSTERS,
    PROFILE_ID,
    SKIP_CONFIGURATION,
)

_LOGGER = logging.getLogger(__name__)

XIAOMI_PROFILE_ID = 0xA1E0
XIAOMI_DEVICE_TYPE = 0x61


class Plug(XiaomiCustomDevice):
    """lumi.plug.mmeu01 plug."""

    def __init__(self, *args, **kwargs):
        """Init."""
        self.voltage_bus = Bus()
        self.consumption_bus = Bus()
        self.power_bus = Bus()
        super().__init__(*args, **kwargs)

    signature = {
        MODELS_INFO: [(LUMI, "lumi.plug.mmeu01")],
        ENDPOINTS: {
            # <SimpleDescriptor endpoint=1 profile=260 device_type=81
            # device_version=1
            # input_clusters=[0, 2, 3, 4, 5, 6, 9, 1794, 2820]
            # output_clusters=[10, 25]>
            1: {
                PROFILE_ID: zha.PROFILE_ID,
                DEVICE_TYPE: zha.DeviceType.SMART_PLUG,
                INPUT_CLUSTERS: [
                    Basic.cluster_id,
                    DeviceTemperature.cluster_id,
                    Identify.cluster_id,
                    Groups.cluster_id,
                    Scenes.cluster_id,
                    OnOff.cluster_id,
                    Alarms.cluster_id,
                    Metering.cluster_id,
                    ElectricalMeasurement.cluster_id,
                ],
                OUTPUT_CLUSTERS: [Time.cluster_id, Ota.cluster_id],
            },
            # <SimpleDescriptor endpoint=242 profile=41440 device_type=97
            # device_version=0
            # input_clusters=[]
            # output_clusters=[33]>
            242: {
                PROFILE_ID: XIAOMI_PROFILE_ID,
                DEVICE_TYPE: XIAOMI_DEVICE_TYPE,
                OUTPUT_CLUSTERS: [GreenPowerProxy.cluster_id],
            },
        },
    }
    replacement = {
        SKIP_CONFIGURATION: True,
        ENDPOINTS: {
            1: {
                PROFILE_ID: zha.PROFILE_ID,
                DEVICE_TYPE: zha.DeviceType.SMART_PLUG,
                INPUT_CLUSTERS: [
                    BasicCluster,
                    DeviceTemperature.cluster_id,
                    Identify.cluster_id,
                    Groups.cluster_id,
                    Scenes.cluster_id,
                    OnOff.cluster_id,
                    Alarms.cluster_id,
                    Metering.cluster_id,
                    ElectricalMeasurementCluster,
                ],
                OUTPUT_CLUSTERS: [Time.cluster_id, Ota.cluster_id],
            },
            21: {
                PROFILE_ID: zha.PROFILE_ID,
                DEVICE_TYPE: zha.DeviceType.MAIN_POWER_OUTLET,
                INPUT_CLUSTERS: [AnalogInputCluster],
                OUTPUT_CLUSTERS: [AnalogInput.cluster_id, Groups.cluster_id],
            },
            242: {
                PROFILE_ID: XIAOMI_PROFILE_ID,
                DEVICE_TYPE: XIAOMI_DEVICE_TYPE,
                OUTPUT_CLUSTERS: [GreenPowerProxy.cluster_id],
            },
        },
    }
```

I just bought 3 of these for Australia and this is my signature and had them connected on the latest version of HA.

Um using Sonoff Zigbee ZHA Coordinator

I have not changed the quirk. Thats how it was

manufacturer": "LUMI",
  "model": "lumi.plug",
  "class": "zhaquirks.xiaomi.aqara.plug.Plug"
![Screenshot_20220317-203314](https://user-images.githubusercontent.com/58960644/158882913-482af6eb-5906-4089-9a0f-877e829b627a.png)

@cloudbr34k84 your screenshot is not loading
> @cloudbr34k84 your screenshot is not loading

Sorted, thanks mate 
@cloudbr34k84, let me see if I understand you correctly. Are you saying that you have three "lumi.plug.maeu01" integrated on the latest build of HA; and on which HA version (if you can remember) did you initially start using them? Did you change the quirk or is this how it got configured? 

I bought mine quite recently and this is my configuration with a Conbee II:
![Screenshot_20220318-021040_Home Assistant](https://user-images.githubusercontent.com/75570119/158918509-e253d651-cb9f-4b7f-b669-60585870a478.jpg)
> @cloudbr34k84, let me see if I understand you correctly. Are you saying that you have three "lumi.plug.maeu01" integrated on the latest build of HA; and on which HA version (if you can remember) did you initially start using them? Did you change the quirk or is this how it got configured?
> 
> I bought mine quite recently and this is my configuration with a Conbee II: ![Screenshot_20220318-021040_Home Assistant](https://user-images.githubusercontent.com/75570119/158918509-e253d651-cb9f-4b7f-b669-60585870a478.jpg)

Hey sorry mate, i have updated my original post and answered these questions.
> Hey sorry mate, i have updated my original post and answered these questions.

Cheers mate. Interesting. I'm just guessing now, so either the AU plugs hardware is not 100% equal to the EU version or they might use significantly different firmware.

Does anyone know if you can manually change the quirk? 
The following issue seems to be linked/same as this one:
[https://github.com/home-assistant/core/issues/65292](url)
I had the same problem with a freshly installed Home Assistant (running as a container on a RPi 4 with ZHA and a RaspBee II) and the SP-EUC01 Aqara smart plug.

> For the maeu01 models: I am fairly certain I know what is wrong. is anyone willing to try to modify the quirk locally? if so, remove this line:
> 
> https://github.com/zigpy/zha-device-handlers/blob/b0bbbfb6b1f267b7d87d833b1ba5a5b0b127a9a1/zhaquirks/xiaomi/aqara/plug_mmeu01.py#L93
> , then save the file and restart HA. After HA is back up, reconfigure the device via the reconfigure button on the device card.
> 
> z2m binds the clusters on these: https://github.com/Koenkk/zigbee-herdsman-converters/blob/66bfcdc9405abebe70906b279e96f12de73f26a7/devices/xiaomi.js#L1048

 After applying this patch, most identified sensors are still showing "Not available" – however `smartenergy_metering_summation_delivered` now actually shows a value whereas before it was dead too.

What I find strange is the alleged device temperature value of 0,2°C which doesn't make any sense.

![Screen Shot 2022-03-22 at 11 54 14](https://user-images.githubusercontent.com/16653872/159466555-a35243b9-07c0-47ef-bd1a-724198cacf36.png)


@dmulcahey ..summarizing an unwanted breaking change in 2022.m.r has pushed aqara plug into the "red water", adding lumi.plug.maeu01 in the quirks models list has not been enough to rescue the plug.


Hi, I purchased 3 of these EU plugs today hoping to monitor a few of my appliances.

I've got the following HA setup:
```
Version | core-2022.3.6
-- | --
Installation Type | Home Assistant Container
Development | false
Supervisor | false
Docker | true
User | root
Virtual Environment | false
Python Version | 3.9.9
Operating System Family | Linux
Operating System Version | 5.16.15-arch1-1
CPU Architecture | x86_64
Timezone | Europe/Oslo
```
Using `SONOFF ZigBee 3.0`

After going through all the comments I was able to get the plugs to report summed metering, but that's it.
Following these steps.
1. Comment out: https://github.com/zigpy/zha-device-handlers/blob/b0bbbfb6b1f267b7d87d833b1ba5a5b0b127a9a1/zhaquirks/xiaomi/aqara/plug_mmeu01.py#L93
2. Remove existing device from the ZHA integration
3. Add device

Before commenting out `SKIP_CONFIGURATION`:
![image](https://user-images.githubusercontent.com/554229/159552905-ef161c4a-6af0-4bbc-957a-5bcb390f9213.png)



After commenting out `SKIP_CONFIGURATION`:
![image](https://user-images.githubusercontent.com/554229/159552845-686e14e7-975b-48f8-97d1-fa15117d7631.png)
 
@husjon Hi, but here we are still missing a fundamental sensor: active power, and I'm quite sure a multiplier factor  x100 on device temperature.
@Stefano0042, yep. I was mainly adding my comment as a summary of what was mentioned previously.
I'm still hoping for a solution as I mainly bought these plugs for appliance monitoring in addition to the switching.

I haven't been able to do much troubleshooting lately, but if someone could point me in the right direction I'll try to assist as needed.
I have the same problem with newly added plugs. First one i bought and connect in January works well. Others were bought & connected in february and these are not working. All sensors are unavailable.   

First plug connected in January (dont remember version of HA) is still working well
![Screenshot from 2022-03-25 09 37 03](https://user-images.githubusercontent.com/11133173/160085221-265e2c39-c9d5-4f63-a2e4-ee56e10c0db1.png)

Lately installed are unavailable - only on/off is available
![Screenshot from 2022-03-25 09 38 07](https://user-images.githubusercontent.com/11133173/160085252-d31fbf0a-4842-4d49-8026-b09c179c2266.png)
Hello, today I got my Aqara socket, and its currently also not working...

<img width="666" alt="image" src="https://user-images.githubusercontent.com/87038988/160187614-ba499c85-f3e5-4bb2-adcb-2558a90114a8.png">


Resolving patch:
diff --git a/zhaquirks/xiaomi/aqara/plug_mmeu01.py b/zhaquirks/xiaomi/aqara/plug_mmeu01.py
--- a/zhaquirks/xiaomi/aqara/plug_mmeu01.py
+++ b/zhaquirks/xiaomi/aqara/plug_mmeu01.py
@@ -2,6 +2,7 @@
 import logging
 
 from zigpy.profiles import zha
+import zigpy.types as types
 from zigpy.zcl.clusters.general import (
     Alarms,
     AnalogInput,
@@ -33,6 +34,7 @@
     AnalogInputCluster,
     BasicCluster,
     ElectricalMeasurementCluster,
+    XiaomiAqaraE1Cluster,
     XiaomiCustomDevice,
 )
 
@@ -40,6 +42,7 @@
 
 XIAOMI_PROFILE_ID = 0xA1E0
 XIAOMI_DEVICE_TYPE = 0x61
+OPPLE_MFG_CODE = 0x115F
 
 
 class Plug(XiaomiCustomDevice):
@@ -55,7 +58,6 @@ def __init__(self, *args, **kwargs):
     signature = {
         MODELS_INFO: [
             (LUMI, "lumi.plug.mmeu01"),
-            (LUMI, "lumi.plug.maeu01"),
         ],
         ENDPOINTS: {
             # <SimpleDescriptor endpoint=1 profile=260 device_type=81
@@ -121,3 +123,58 @@ def __init__(self, *args, **kwargs):
             },
         },
     }
+
+
+class OppleCluster(XiaomiAqaraE1Cluster):
+    """Opple cluster."""
+
+    ep_attribute = "opple_cluster"
+    attributes = {
+        0x0009: ("mode", types.uint8_t, True),
+    }
+    attr_config = {0x0009: 0x00}
+
+    async def bind(self):
+        """Bind cluster."""
+        result = await super().bind()
+        await self.write_attributes(self.attr_config, manufacturer=OPPLE_MFG_CODE)
+        return result
+
+
+class PlugMAEU01(Plug):
+    """lumi.plug.maeu01 plug."""
+
+    signature = {
+        MODELS_INFO: [
+            (LUMI, "lumi.plug.maeu01"),
+        ],
+        ENDPOINTS: Plug.signature[ENDPOINTS],
+    }
+
+    replacement = {
+        SKIP_CONFIGURATION: False,
+        ENDPOINTS: {
+            1: {
+                PROFILE_ID: zha.PROFILE_ID,
+                DEVICE_TYPE: zha.DeviceType.SMART_PLUG,
+                INPUT_CLUSTERS: [
+                    Basic.cluster_id,
+                    DeviceTemperature.cluster_id,
+                    Identify.cluster_id,
+                    Groups.cluster_id,
+                    Scenes.cluster_id,
+                    OnOff.cluster_id,
+                    Alarms.cluster_id,
+                    Metering.cluster_id,
+                    ElectricalMeasurement.cluster_id,
+                    OppleCluster,
+                ],
+                OUTPUT_CLUSTERS: [Time.cluster_id, Ota.cluster_id],
+            },
+            242: {
+                PROFILE_ID: XIAOMI_PROFILE_ID,
+                DEVICE_TYPE: XIAOMI_DEVICE_TYPE,
+                OUTPUT_CLUSTERS: [GreenPowerProxy.cluster_id],
+            },
+        },
+    }


Test patch: