From 2e27e6622482886babbeb9e9918e3be95634381a Mon Sep 17 00:00:00 2001 From: Marc-Olivier Arsenault Date: Mon, 4 Dec 2023 20:37:20 -0500 Subject: [PATCH] add protection for dividing by zero (#240) --- custom_components/moonraker/sensor.py | 3 +++ tests/test_sensor.py | 29 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/custom_components/moonraker/sensor.py b/custom_components/moonraker/sensor.py index ad0e566..63a2f13 100755 --- a/custom_components/moonraker/sensor.py +++ b/custom_components/moonraker/sensor.py @@ -571,6 +571,9 @@ def calculate_current_layer(data): ): return data["status"]["print_stats"]["info"]["current_layer"] + if "layer_height" not in data or data["layer_height"] <= 0: + return 0 + # layer = (current_z - first_layer_height) / layer_height + 1 return ( int( diff --git a/tests/test_sensor.py b/tests/test_sensor.py index c615450..d1d4b68 100755 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -338,6 +338,35 @@ async def test_current_layer_calculated(): assert calculate_current_layer(data) == 42 +async def test_current_layer_calculated_layer_height_0(): + data = { + "status": { + "print_stats": { + "state": PRINTSTATES.PRINTING.value, + "filename": "TheUniverse.gcode", + }, + "toolhead": {"position": [0, 0, 8.4]}, + }, + "first_layer_height": 0.2, + "layer_height": 0, + } + assert calculate_current_layer(data) == 0 + + +async def test_current_layer_calculate_missing_layer_height(): + data = { + "status": { + "print_stats": { + "state": PRINTSTATES.PRINTING.value, + "filename": "TheUniverse.gcode", + }, + "toolhead": {"position": [0, 0, 8.4]}, + }, + "first_layer_height": 0.2, + } + assert calculate_current_layer(data) == 0 + + async def test_current_layer_calculated_partial_info(): data = { "status": {