Skip to content

Commit

Permalink
Merge pull request #498 from greghesp/develop
Browse files Browse the repository at this point in the history
Merge develop -> main
  • Loading branch information
AdrianGarside authored Apr 16, 2024
2 parents 254e91e + 7ce9992 commit 4bcb61f
Show file tree
Hide file tree
Showing 6 changed files with 182 additions and 152 deletions.
106 changes: 60 additions & 46 deletions custom_components/bambu_lab/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class BambuDataUpdateCoordinator(DataUpdateCoordinator):

def __init__(self, hass, *, entry: ConfigEntry) -> None:
self._hass = hass
self._entry = entry
LOGGER.debug(f"ConfigEntry.Id: {entry.entry_id}")

self.latest_usage_hours = float(entry.options.get('usage_hours', 0))
Expand All @@ -49,73 +50,86 @@ def __init__(self, hass, *, entry: ConfigEntry) -> None:

self._updatedDevice = False
self.data = self.get_model()
self._eventloop = asyncio.get_running_loop()
super().__init__(
hass,
LOGGER,
name=DOMAIN,
update_interval=SCAN_INTERVAL
)

self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._async_shutdown)

@callback
async def start_mqtt(self) -> None:
"""Use MQTT for updates."""
LOGGER.debug("Starting MQTT")
def _async_shutdown(self, event: Event) -> None:
"""Call when Home Assistant is stopping."""
LOGGER.debug(f"HOME ASSISTANT IS SHUTTING DOWN")
self.shutdown()

def event_handler(event):
if event == "event_printer_info_update":
self._update_device_info()
if self.get_model().supports_feature(Features.EXTERNAL_SPOOL):
self._update_external_spool_info()
def event_handler(self, event):
# The callback comes in on the MQTT thread. Need to jump to the HA main thread to guarantee thread safety.
self._eventloop.call_soon_threadsafe(self.event_handler_internal, event)

elif event == "event_ams_info_update":
self._update_ams_info()
def event_handler_internal(self, event):
LOGGER.debug(f"EVENT: {event}")
if event == "event_printer_info_update":
self._update_device_info()
if self.get_model().supports_feature(Features.EXTERNAL_SPOOL):
self._update_external_spool_info()

elif event == "event_light_update":
self._update_data()
elif event == "event_ams_info_update":
self._update_ams_info()

elif event == "event_speed_update":
self._update_data()
elif event == "event_light_update":
self._update_data()

elif event == "event_printer_data_update":
self._update_data()
elif event == "event_speed_update":
self._update_data()

# Check is usage hours change and persist to config entry if it did.
if self.latest_usage_hours != self.get_model().info.usage_hours:
self.latest_usage_hours = self.get_model().info.usage_hours
LOGGER.debug(f"OVERWRITING USAGE_HOURS WITH : {self.latest_usage_hours}")
options = dict(self.config_entry.options)
options['usage_hours'] = self.latest_usage_hours
self._hass.config_entries.async_update_entry(
entry=self.config_entry,
title=self.get_model().info.serial,
data=self.config_entry.data,
options=options)
elif event == "event_printer_data_update":
self._update_data()

elif event == "event_hms_errors":
self._update_hms()
# Check is usage hours change and persist to config entry if it did.
if self.latest_usage_hours != self.get_model().info.usage_hours:
self.latest_usage_hours = self.get_model().info.usage_hours
LOGGER.debug(f"OVERWRITING USAGE_HOURS WITH : {self.latest_usage_hours}")
options = dict(self.config_entry.options)
options['usage_hours'] = self.latest_usage_hours
self._hass.config_entries.async_update_entry(
entry=self.config_entry,
title=self.get_model().info.serial,
data=self.config_entry.data,
options=options)

elif event == "event_print_canceled":
self.PublishDeviceTriggerEvent(event)
elif event == "event_hms_errors":
self._update_hms()

elif event == "event_print_failed":
self.PublishDeviceTriggerEvent(event)
elif event == "event_print_canceled":
self.PublishDeviceTriggerEvent(event)

elif event == "event_print_finished":
self.PublishDeviceTriggerEvent(event)
elif event == "event_print_failed":
self.PublishDeviceTriggerEvent(event)

elif event == "event_print_started":
self.PublishDeviceTriggerEvent(event)
elif event == "event_print_finished":
self.PublishDeviceTriggerEvent(event)

elif event == "event_printer_chamber_image_update":
self._update_data()
elif event == "event_print_started":
self.PublishDeviceTriggerEvent(event)

elif event == "event_printer_cover_image_update":
self._update_data()
elif event == "event_printer_chamber_image_update":
self._update_data()

async def listen():
self.client.connect(callback=event_handler)
elif event == "event_printer_cover_image_update":
self._update_data()

asyncio.create_task(listen())
async def listen(self):
LOGGER.debug("Starting listen()")
self.client.connect(callback=self.event_handler)

async def start_mqtt(self) -> None:
"""Use MQTT for updates."""
LOGGER.debug("Starting MQTT")
asyncio.create_task(self.listen())

def shutdown(self) -> None:
""" Halt the MQTT listener thread """
Expand Down Expand Up @@ -143,15 +157,15 @@ def _update_hms(self):
hadevice = dev_reg.async_get_device(identifiers={(DOMAIN, self.get_model().info.serial)})

device = self.get_model()
if device.hms.count == 0:
if device.hms.error_count == 0:
event_data = {
"device_id": hadevice.id,
"type": "event_printer_error_cleared",
}
LOGGER.debug(f"EVENT: HMS errors cleared: {event_data}")
self._hass.bus.async_fire(f"{DOMAIN}_event", event_data)
else:
for index in range (device.hms.count):
for index in range (device.hms.error_count):
event_data = {
"device_id": hadevice.id,
"type": "event_printer_error",
Expand Down
2 changes: 1 addition & 1 deletion custom_components/bambu_lab/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class BambuLabBinarySensorEntityDescription(BinarySensorEntityDescription, Bambu
translation_key="hms_errors",
device_class=BinarySensorDeviceClass.PROBLEM,
entity_category=EntityCategory.DIAGNOSTIC,
is_on_fn=lambda self: self.coordinator.get_model().hms.count != 0,
is_on_fn=lambda self: self.coordinator.get_model().hms.error_count != 0,
extra_attributes=lambda self: self.coordinator.get_model().hms.errors
),
BambuLabBinarySensorEntityDescription(
Expand Down
2 changes: 1 addition & 1 deletion custom_components/bambu_lab/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@
"st": "urn:bambulab-com:device:3dprinter:1"
}
],
"version": "2.0.15"
"version": "2.0.16"
}
Loading

0 comments on commit 4bcb61f

Please sign in to comment.