sopelj / hass-ember-mug-component

Ember Mug Integration for Home Assistant
MIT License
116 stars 4 forks source link

Object of type MugFirmwareInfo is not JSON serializable #47

Closed RedEarth1 closed 9 months ago

RedEarth1 commented 10 months ago

Description

I have MQTT Statestream enabled in Home Assistant, and the Ember Mug Integration is causing errors each time the mug state changes because MugFirmwareInfo is not JSON serializable. I have had to temporarily exclude the mug state in the MQTT statestream config using an entity glob, this prevents the errors.

Logs / Errors

2024-02-03 18:11:12.415 INFO (MainThread) [ember_mug.mug] Subscribe to Push Events
2024-02-03 18:11:19.763 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/mqtt_statestream/__init__.py", line 86, in _state_publisher
    encoded_val = json.dumps(val, cls=JSONEncoder)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
          ^^^^^^^^^^^
  File "/usr/local/lib/python3.11/json/encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/json/encoder.py", line 258, in iterencode
    return _iterencode(o, 0)
           ^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/json.py", line 40, in default
    return json.JSONEncoder.default(self, o)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/json/encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type MugFirmwareInfo is not JSON serializable
sopelj commented 10 months ago

Hey. That does make sense as the object is not JSON serializable. It's surprising that is just blindly tries to dump the state into a JSON encoder, it could easily be serialized by using todict. Many integrations use dataclasses for passing data, so I'm surprised there aren't problems more often. I'll have a look to see what I can do, but this requires a few changes to both this integration and the base library just to be compatible with this other integration.

sopelj commented 9 months ago

Oh ok, it turns out this isn't too major as the encoder in Home Assistant has some support for custom methods. I think it should work now as of 1.0.0 beta-2.

RedEarth1 commented 9 months ago

Hi, I've tried 1.0.0 beta-2 and I think your fix has solved the problem. The error has stopped appearing in the HA logs and I can now see the mug firmware being reported on the MQTT statestream in MQTT explorer. Thanks for looking into it

sopelj commented 9 months ago

Awesome! Thanks for pointing it out. I'll close this then, but don't hesitate if you have other issues.