Skip to content

Home Information - Your home, your data, organized.

Python

Issue #316: Threshold-based EventClause for continuous-value alarms (#318)

Tony C9e3502312e5d
diff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.md
index e593a2f7..a554306f 100644
--- a/docs/dev/integrations/integration-guidelines.md
+++ b/docs/dev/integrations/integration-guidelines.md
@@ -64,7 +64,9 @@ The model-level factories in `hi.apps.model_helper.HiModelHelper` (`create_movem
Use this for the common case of sharing the sensor's integration_key with its alarm event. If an integration needs a *different* integration_key for the alarm event (e.g., ZoneMinder's separate `MOVEMENT_EVENT_PREFIX`), leave the flag False and call the matching `create_*_event_definition` explicitly with the alternate key.
-The default alarm definitions are a starting point — the user can customize windows, dedupe, levels, etc. after import. The integration's role is to provide a reasonable default, not a final policy.
+The default alarm definitions are a starting point — the user can customize entity_state, value, operator, windows, dedupe, and alarm levels through the event-definition edit UI. The integration's role is to provide a reasonable default, not a final policy.
+
+For continuous-value EntityStateTypes (`BATTERY_LEVEL` percentage, future temperature / humidity out-of-range, etc.), `EventClause` carries an `EventClauseOperator` (`EQ` / `LT` / `LTE` / `GT` / `GTE`) so alarms can fire on threshold crossings instead of exact-value matches. The integration uses a dedicated factory like `create_battery_level_event_definition`; the operator and threshold are otherwise transparent.
## Integration Setup Process
diff --git a/src/hi/apps/event/edit/forms.py b/src/hi/apps/event/edit/forms.py
index ddc526c6..755fbb2c 100644
--- a/src/hi/apps/event/edit/forms.py
+++ b/src/hi/apps/event/edit/forms.py
@@ -7,7 +7,7 @@ from hi.apps.control.models import Controller
from hi.apps.common.forms import CustomBaseFormSet
from hi.apps.entity.edit.forms import EntityStateSelectModelFormMixin
from hi.apps.entity.models import EntityState
-from hi.apps.event.enums import EventType
+from hi.apps.event.enums import EventClauseOperator, EventType
import hi.apps.event.models as models
from hi.apps.security.enums import SecurityLevel
@@ -41,9 +41,18 @@ class EventClauseForm( forms.ModelForm, EntityStateSelectModelFormMixin ):
model = models.EventClause
fields = (
'entity_state',
+ 'value_operator_str',
'value',
)
+ value_operator_str = forms.ChoiceField(
+ label = 'Operator',
+ choices = EventClauseOperator.choices,
+ initial = EventClauseOperator.default_value(),
+ required = True,
+ widget = forms.Select( attrs = { 'class' : 'custom-select' } ),
+ )
+
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
entity_state = self.get_instance( cls = EntityState, field_name = 'entity_state' )
@@ -54,7 +63,35 @@ class EventClauseForm( forms.ModelForm, EntityStateSelectModelFormMixin ):
)
self.fields['entity_state'].widget.attrs.update({ 'class': 'custom-select' })
self.fields['value'].widget.attrs.update({ 'class': 'custom-select' })
+ # When the operator changes, swap the value widget to a numeric
+ # input (for non-EQ) so threshold clauses are editable on the
+ # spot. EQ leaves whatever widget the entity_state-driven swap
+ # rendered (Select for discrete states, text input otherwise).
+ value_field_id = f'id_{self.prefix}-value' if self.prefix else 'id_value'
+ operator_field_id = f'id_{self.prefix}-value_operator_str' if self.prefix else 'id_value_operator_str'
+ self.fields['value_operator_str'].widget.attrs['onchange'] = (
+ f'Hi.setEventClauseValueOperatorWidget('
+ f'"{operator_field_id}", "{value_field_id}");'
+ )
return
+
+ def clean(self):
+ cleaned = super().clean()
+ op_str = cleaned.get( 'value_operator_str' )
+ value = cleaned.get( 'value' )
+ # Numeric operators require a numeric value. The matcher silently
+ # no-ops on parse failure at runtime; reject at form time so the
+ # user gets immediate feedback instead of a clause that never
+ # fires.
+ if op_str and op_str != str(EventClauseOperator.EQ) and value:
+ try:
+ float( value )
+ except ( ValueError, TypeError ):
+ self.add_error(
+ 'value',
+ f'Numeric value required for operator "{op_str}".',
+ )
+ return cleaned
class AlarmActionForm( forms.ModelForm ):
diff --git a/src/hi/apps/event/edit/tests/test_forms.py b/src/hi/apps/event/edit/tests/test_forms.py
new file mode 100644
index 00000000..f16128bc
--- /dev/null
+++ b/src/hi/apps/event/edit/tests/test_forms.py
@@ -0,0 +1,46 @@
+import logging
+
+from hi.apps.entity.models import Entity, EntityState
+from hi.apps.event.edit.forms import EventClauseForm
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEventClauseFormValidation(BaseTestCase):
+ """The matcher silently no-ops on non-numeric values under numeric
+ operators (LT / LTE / GT / GTE) — without form-time rejection, a
+ user could save a clause that never fires. Validate the form-level
+ guard so the silent-failure mode can't slip past the UI."""
+
+ def setUp(self):
+ super().setUp()
+ entity = Entity.objects.create(
+ name = 'Test Entity',
+ entity_type_str = 'switch',
+ )
+ self.entity_state = EntityState.objects.create(
+ entity = entity,
+ name = 'Battery',
+ entity_state_type_str = 'battery_level',
+ )
+ return
+
+ def test_non_numeric_value_with_lt_operator_is_rejected(self):
+ form = EventClauseForm( data = {
+ 'entity_state': str( self.entity_state.id ),
+ 'value_operator_str': 'lt',
+ 'value': 'abc',
+ })
+ self.assertFalse( form.is_valid() )
+ self.assertIn( 'value', form.errors )
+ return
+
+ def test_numeric_value_with_lt_operator_is_accepted(self):
+ form = EventClauseForm( data = {
+ 'entity_state': str( self.entity_state.id ),
+ 'value_operator_str': 'lt',
+ 'value': '20.5',
+ })
+ self.assertTrue( form.is_valid(), msg = form.errors )
+ return
diff --git a/src/hi/apps/event/edit/tests/test_views.py b/src/hi/apps/event/edit/tests/test_views.py
index d6f4cfb5..1a01febf 100644
--- a/src/hi/apps/event/edit/tests/test_views.py
+++ b/src/hi/apps/event/edit/tests/test_views.py
@@ -113,6 +113,7 @@ class TestEventDefinitionEditView(DualModeViewTestCase):
'event-clause-MIN_NUM_FORMS': '0',
'event-clause-MAX_NUM_FORMS': '1000',
'event-clause-0-entity_state': str(self.test_entity_state.id),
+ 'event-clause-0-value_operator_str': 'eq',
'event-clause-0-value': 'on',
# Alarm action formset (required to have at least one alarm or control action)
@@ -176,6 +177,7 @@ class TestEventDefinitionEditView(DualModeViewTestCase):
'event-clause-MIN_NUM_FORMS': '0',
'event-clause-MAX_NUM_FORMS': '1000',
'event-clause-0-entity_state': str(self.test_entity_state.id),
+ 'event-clause-0-value_operator_str': 'eq',
'event-clause-0-value': 'on',
# Alarm action formset
@@ -278,6 +280,7 @@ class TestEventDefinitionEditView(DualModeViewTestCase):
'event-clause-MIN_NUM_FORMS': '0',
'event-clause-MAX_NUM_FORMS': '1000',
'event-clause-0-entity_state': str(self.test_entity_state.id),
+ 'event-clause-0-value_operator_str': 'eq',
'event-clause-0-value': 'on',
# No alarm actions
@@ -401,6 +404,7 @@ class TestEventDefinitionAddView(DualModeViewTestCase):
'event-clause-MIN_NUM_FORMS': '0',
'event-clause-MAX_NUM_FORMS': '1000',
'event-clause-0-entity_state': str(self.test_entity_state.id),
+ 'event-clause-0-value_operator_str': 'eq',
'event-clause-0-value': 'off',
# Alarm action formset (required to have at least one alarm or control action)
diff --git a/src/hi/apps/event/enums.py b/src/hi/apps/event/enums.py
index d8d3efe8..71477dee 100644
--- a/src/hi/apps/event/enums.py
+++ b/src/hi/apps/event/enums.py
@@ -2,9 +2,29 @@ from hi.apps.common.enums import LabeledEnum
class EventType(LabeledEnum):
-
- SECURITY = ( 'Security' , '' )
+
+ SECURITY = ( 'Security' , '' )
MAINTENANCE = ( 'Maintenance' , '' )
INFORMATION = ( 'Information' , '' )
- AUTOMATION = ( 'Automation' , '' )
-
+ AUTOMATION = ( 'Automation' , '' )
+
+
+class EventClauseOperator(LabeledEnum):
+ """How an EventClause compares the live wire value against its
+ stored target value. EQ matches a discrete value (motion ACTIVE,
+ smoke SMOKE_DETECTED, etc.); the numeric operators trigger when
+ a continuous reading crosses a threshold (battery < 20%, etc.).
+ Numeric ops parse both sides via ``float()`` at match time and
+ silently no-op on parse failure so a malformed wire value never
+ raises into the matcher."""
+
+ EQ = ( 'Equals' , 'Trigger when the value equals the target string.' )
+ LT = ( 'Less Than' , 'Trigger when the numeric value drops below the threshold.' )
+ LTE = ( 'At Most' , 'Trigger when the numeric value is at or below the threshold.' )
+ GT = ( 'Greater Than' , 'Trigger when the numeric value rises above the threshold.' )
+ GTE = ( 'At Least' , 'Trigger when the numeric value is at or above the threshold.' )
+
+ @classmethod
+ def default(cls):
+ return cls.EQ
+
diff --git a/src/hi/apps/event/event_manager.py b/src/hi/apps/event/event_manager.py
index 9bf4bbba..e94a0365 100644
--- a/src/hi/apps/event/event_manager.py
+++ b/src/hi/apps/event/event_manager.py
@@ -18,7 +18,7 @@ from hi.apps.security.security_mixins import SecurityMixin
from hi.integrations.transient_models import IntegrationKey
-from .enums import EventType
+from .enums import EventClauseOperator, EventType
from .models import AlarmAction, EventClause, EventDefinition, EventHistory
from .transient_models import Event, EntityStateTransition
@@ -127,7 +127,8 @@ class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):
for transition in self._recent_transitions:
if transition.entity_state != event_clause.entity_state:
continue
- if transition.latest_sensor_response.value != event_clause.value:
+ if not self._clause_matches(
+ transition.latest_sensor_response.value, event_clause ):
continue
transition_timedelta = current_timestamp - transition.timestamp
if transition_timedelta.total_seconds() > event_definition.event_window_secs:
@@ -144,6 +145,41 @@ class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):
sensor_response_list = sensor_response_list,
)
+ @staticmethod
+ def _clause_matches( entity_state_value : str, event_clause : EventClause ) -> bool:
+ """Compare a live EntityState reading against an EventClause
+ target per the clause's operator. EQ is plain string equality
+ (the historical behavior for discrete-value alarms). The
+ numeric operators parse both sides as ``float()`` and silently
+ no-op on parse failure so a transient non-numeric reading
+ never raises into the matcher."""
+ op = event_clause.value_operator
+ if op == EventClauseOperator.EQ:
+ return entity_state_value == event_clause.value
+ try:
+ lhs = float( entity_state_value )
+ rhs = float( event_clause.value )
+ except ( ValueError, TypeError ):
+ # DEBUG, not WARNING: HA emits transient 'unknown' /
+ # 'unavailable' as sensor values; promoting this would
+ # spam every reconnect cycle. A misconfigured threshold
+ # remains diagnosable by enabling DEBUG on this logger.
+ logger.debug(
+ f'Threshold clause skipped: non-numeric value '
+ f'{entity_state_value!r} vs clause {event_clause.id} '
+ f'target {event_clause.value!r} op {op}.'
+ )
+ return False
+ if op == EventClauseOperator.LT:
+ return lhs < rhs
+ if op == EventClauseOperator.LTE:
+ return lhs <= rhs
+ if op == EventClauseOperator.GT:
+ return lhs > rhs
+ if op == EventClauseOperator.GTE:
+ return lhs >= rhs
+ return False
+
def _purge_old_transitions( self ):
current_timestamp = datetimeproxy.now()
@@ -206,7 +242,9 @@ class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):
event_window_secs : int,
dedupe_window_secs : int,
alarm_lifetime_secs : int,
- integration_key : IntegrationKey = None ) -> EventDefinition:
+ integration_key : IntegrationKey = None,
+ value_operator : EventClauseOperator = EventClauseOperator.EQ,
+ ) -> EventDefinition:
with transaction.atomic():
event_definition = EventDefinition(
@@ -223,6 +261,7 @@ class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):
event_definition = event_definition,
entity_state = entity_state,
value = value,
+ value_operator_str = str(value_operator),
)
for security_level, alarm_level in security_to_alarm_level.items():
_ = AlarmAction.objects.create(
diff --git a/src/hi/apps/event/migrations/0008_add_eventclause_value_operator.py b/src/hi/apps/event/migrations/0008_add_eventclause_value_operator.py
new file mode 100644
index 00000000..b8115dad
--- /dev/null
+++ b/src/hi/apps/event/migrations/0008_add_eventclause_value_operator.py
@@ -0,0 +1,18 @@
+# Generated by Django 4.2.30 on 2026-05-12 02:24
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("event", "0007_replace_zero_alarm_lifetime"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="eventclause",
+ name="value_operator_str",
+ field=models.CharField(default="eq", max_length=8, verbose_name="Operator"),
+ ),
+ ]
diff --git a/src/hi/apps/event/models.py b/src/hi/apps/event/models.py
index c82dd87e..cc5a310a 100644
--- a/src/hi/apps/event/models.py
+++ b/src/hi/apps/event/models.py
@@ -24,7 +24,7 @@ from hi.apps.security.enums import SecurityLevel
from hi.integrations.models import IntegrationDetailsModel
-from .enums import EventType
+from .enums import EventClauseOperator, EventType
class EventDefinition( IntegrationDetailsModel ):
@@ -100,6 +100,17 @@ class EventClause( models.Model ):
'Value',
max_length = 255
)
+ # How ``value`` is compared against the live wire reading.
+ # Default ``'EQ'`` keeps every pre-threshold clause matching by
+ # exact string equality (the historical behavior). Numeric
+ # operators (LT / LTE / GT / GTE) enable threshold-based alarms
+ # on continuous EntityStateTypes such as BATTERY_LEVEL.
+ value_operator_str = models.CharField(
+ 'Operator',
+ max_length = 8,
+ default = str(EventClauseOperator.default()),
+ null = False, blank = False,
+ )
created_datetime = models.DateTimeField(
'Created',
auto_now_add = True,
@@ -110,11 +121,20 @@ class EventClause( models.Model ):
auto_now = True,
blank = True,
)
-
+
class Meta:
verbose_name = 'Trigger Clause'
verbose_name_plural = 'Trigger Clauses'
+ @property
+ def value_operator(self) -> EventClauseOperator:
+ return EventClauseOperator.from_name_safe( self.value_operator_str )
+
+ @value_operator.setter
+ def value_operator( self, value_operator : EventClauseOperator ):
+ self.value_operator_str = str(value_operator)
+ return
+
class AlarmAction( models.Model ):
diff --git a/src/hi/apps/event/templates/event/edit/panes/event_clause_form.html b/src/hi/apps/event/templates/event/edit/panes/event_clause_form.html
index df3e2f60..dfea3024 100644
--- a/src/hi/apps/event/templates/event/edit/panes/event_clause_form.html
+++ b/src/hi/apps/event/templates/event/edit/panes/event_clause_form.html
@@ -37,13 +37,22 @@
<div class="input-group mb-2 mr-sm-2 w-100">
<div class="input-group-prepend" >
- <label for="{{ event_clause_form.entity.id_for_label }}"
+ <label for="{{ event_clause_form.entity_state.id_for_label }}"
class="input-group-text" >{{ event_clause_form.entity_state.label }}</label>
{{ event_clause_form.entity_state }}
<small class="form-error text-danger" >{{ event_clause_form.entity_state.errors }}</small>
</div>
</div>
+ <div class="input-group mb-2 mr-sm-2 w-100">
+ <div class="input-group-prepend" >
+ <label for="{{ event_clause_form.value_operator_str.id_for_label }}"
+ class="input-group-text" >{{ event_clause_form.value_operator_str.label }}</label>
+ {{ event_clause_form.value_operator_str }}
+ <small class="form-error text-danger" >{{ event_clause_form.value_operator_str.errors }}</small>
+ </div>
+ </div>
+
<div class="input-group mb-2 mr-sm-2 w-100">
<div class="input-group-prepend" >
<label for="{{ event_clause_form.value.id_for_label }}"
diff --git a/src/hi/apps/event/tests/test_event_manager.py b/src/hi/apps/event/tests/test_event_manager.py
index 841eec39..6f56de5e 100644
--- a/src/hi/apps/event/tests/test_event_manager.py
+++ b/src/hi/apps/event/tests/test_event_manager.py
@@ -13,7 +13,7 @@ from hi.integrations.transient_models import IntegrationKey
from hi.testing.base_test_case import BaseTestCase
from hi.testing.async_task_utils import AsyncTaskTestCase
-from hi.apps.event.enums import EventType
+from hi.apps.event.enums import EventClauseOperator, EventType
from hi.apps.event.event_manager import EventManager
from hi.apps.event.models import EventDefinition, EventClause, AlarmAction, EventHistory
from hi.apps.event.transient_models import EntityStateTransition, Event
@@ -674,4 +674,54 @@ class TestEventManagerHelperMethods(BaseTestCase):
# Should mark for reload
self.assertTrue(manager._event_definition_reload_needed)
return
-
+
+
+class TestClauseMatchesOperatorDispatch(BaseTestCase):
+ """Direct unit tests for the operator-dispatch in
+ ``EventManager._clause_matches``. The EQ branch is covered
+ end-to-end by ``test_create_event_if_detected_single_clause_match``
+ — the value of this class is exercising the boundary semantics
+ of the numeric operators (LT vs LTE off-by-one risk) and the
+ defensive non-numeric path that prevents transient malformed
+ readings from raising into the matcher."""
+
+ def _clause( self, target_value : str, operator : EventClauseOperator ):
+ clause = EventClause( value = target_value )
+ clause.value_operator = operator
+ return clause
+
+ def test_lt_excludes_boundary( self ):
+ clause = self._clause( '20', EventClauseOperator.LT )
+ self.assertTrue( EventManager._clause_matches( '19', clause ) )
+ self.assertFalse( EventManager._clause_matches( '20', clause ) )
+ self.assertFalse( EventManager._clause_matches( '20.0', clause ) )
+ return
+
+ def test_lte_includes_boundary( self ):
+ clause = self._clause( '20', EventClauseOperator.LTE )
+ self.assertTrue( EventManager._clause_matches( '20', clause ) )
+ self.assertTrue( EventManager._clause_matches( '19', clause ) )
+ self.assertFalse( EventManager._clause_matches( '21', clause ) )
+ return
+
+ def test_gt_excludes_boundary( self ):
+ clause = self._clause( '20', EventClauseOperator.GT )
+ self.assertTrue( EventManager._clause_matches( '21', clause ) )
+ self.assertFalse( EventManager._clause_matches( '20', clause ) )
+ return
+
+ def test_gte_includes_boundary( self ):
+ clause = self._clause( '20', EventClauseOperator.GTE )
+ self.assertTrue( EventManager._clause_matches( '20', clause ) )
+ self.assertTrue( EventManager._clause_matches( '21', clause ) )
+ self.assertFalse( EventManager._clause_matches( '19', clause ) )
+ return
+
+ def test_non_numeric_value_with_numeric_operator_does_not_raise( self ):
+ # A transient malformed entity_state value must not crash the
+ # event-detection loop. Silent False is correct.
+ clause = self._clause( '20', EventClauseOperator.LT )
+ self.assertFalse( EventManager._clause_matches( 'unknown', clause ) )
+ self.assertFalse( EventManager._clause_matches( '', clause ) )
+ return
+
diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.py
index 72486b91..ad6549fb 100644
--- a/src/hi/apps/model_helper.py
+++ b/src/hi/apps/model_helper.py
@@ -12,7 +12,7 @@ from hi.apps.entity.enums import (
TemperatureUnit,
)
from hi.apps.entity.models import Entity, EntityState
-from hi.apps.event.enums import EventType
+from hi.apps.event.enums import EventClauseOperator, EventType
from hi.apps.event.event_manager import EventManager
from hi.apps.event.models import EventDefinition
from hi.apps.security.enums import SecurityLevel
@@ -51,6 +51,16 @@ class HiModelHelper:
DEFAULT_BATTERY_DEDUPE_WINDOW_SECS = 300
DEFAULT_BATTERY_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS
+ # Threshold-based low-battery alarm for continuous BATTERY_LEVEL
+ # percentage sensors. Distinct from the discrete HIGH_LOW battery
+ # alarm above — the threshold uses EventClauseOperator.LT against
+ # a percentage. Dedupe window is one day so a battery flapping
+ # near the threshold doesn't spam.
+ DEFAULT_BATTERY_LEVEL_THRESHOLD_PERCENT = 20
+ DEFAULT_BATTERY_LEVEL_EVENT_WINDOW_SECS = 180
+ DEFAULT_BATTERY_LEVEL_DEDUPE_WINDOW_SECS = 86400
+ DEFAULT_BATTERY_LEVEL_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS
+
DEFAULT_SMOKE_EVENT_WINDOW_SECS = 180
DEFAULT_SMOKE_DEDUPE_WINDOW_SECS = 300
DEFAULT_SMOKE_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS
@@ -363,6 +373,35 @@ class HiModelHelper:
)
return sensor
+ @classmethod
+ def create_battery_level_sensor( cls,
+ entity : Entity,
+ integration_key : IntegrationKey = None,
+ name : str = None,
+ units : str = '%',
+ add_default_alarm : bool = False ) -> Sensor:
+ """Continuous battery-percentage sensor. Mirrors the alarm-bearing
+ sensor factories (smoke / moisture / CO / gas): when
+ ``add_default_alarm`` is True, also wires the canonical
+ low-battery threshold alarm via
+ ``create_battery_level_event_definition``."""
+ if not name:
+ name = f'{entity.name} Battery'
+ sensor = cls.create_sensor(
+ entity = entity,
+ entity_state_type = EntityStateType.BATTERY_LEVEL,
+ name = name,
+ integration_key = integration_key,
+ units = units,
+ )
+ if add_default_alarm:
+ cls.create_battery_level_event_definition(
+ name = f'{sensor.name} Alarm',
+ entity_state = sensor.entity_state,
+ integration_key = integration_key,
+ )
+ return sensor
+
@classmethod
def create_on_off_controller( cls,
entity : Entity,
@@ -774,7 +813,7 @@ class HiModelHelper:
name : str,
entity_state : EntityState,
integration_key : IntegrationKey = None ) -> EventDefinition:
-
+
return EventManager().create_simple_alarm_event_definition(
name = name,
event_type = EventType.MAINTENANCE,
@@ -789,3 +828,34 @@ class HiModelHelper:
alarm_lifetime_secs = cls.DEFAULT_BATTERY_ALARM_LIFETIME_SECS,
integration_key = integration_key,
)
+
+ @classmethod
+ def create_battery_level_event_definition(
+ cls,
+ name : str,
+ entity_state : EntityState,
+ integration_key : IntegrationKey = None,
+ threshold_percent : int = None,
+ ) -> EventDefinition:
+ """Threshold low-battery alarm against a continuous
+ BATTERY_LEVEL percentage sensor. Triggers when the reported
+ percent drops below ``threshold_percent`` (default 20).
+ Distinct from ``create_battery_event_definition`` above, which
+ triggers on the discrete HIGH_LOW battery state."""
+ if threshold_percent is None:
+ threshold_percent = cls.DEFAULT_BATTERY_LEVEL_THRESHOLD_PERCENT
+ return EventManager().create_simple_alarm_event_definition(
+ name = name,
+ event_type = EventType.MAINTENANCE,
+ entity_state = entity_state,
+ value = str( threshold_percent ),
+ value_operator = EventClauseOperator.LT,
+ security_to_alarm_level = {
+ SecurityLevel.HIGH: AlarmLevel.INFO,
+ SecurityLevel.LOW: AlarmLevel.INFO,
+ },
+ event_window_secs = cls.DEFAULT_BATTERY_LEVEL_EVENT_WINDOW_SECS,
+ dedupe_window_secs = cls.DEFAULT_BATTERY_LEVEL_DEDUPE_WINDOW_SECS,
+ alarm_lifetime_secs = cls.DEFAULT_BATTERY_LEVEL_ALARM_LIFETIME_SECS,
+ integration_key = integration_key,
+ )
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index 7ece15e5..aa4ef853 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -1805,15 +1805,17 @@ class HassConverter:
)
elif entity_state_type == EntityStateType.BATTERY_LEVEL:
# HA's battery sensor reports a 0-100 percentage with
- # ``unit_of_measurement='%'``. Store the unit verbatim
- # so the display path renders ``"85%"`` rather than the
- # bare magnitude.
- sensor = HiModelHelper.create_sensor(
+ # ``unit_of_measurement='%'``. Store the unit verbatim so
+ # the display path renders ``"85%"`` rather than the bare
+ # magnitude. With ``add_default_alarm`` the factory also
+ # wires the canonical low-battery threshold alarm
+ # (EventClauseOperator.LT at the default threshold).
+ sensor = HiModelHelper.create_battery_level_sensor(
entity = entity,
- entity_state_type = EntityStateType.BATTERY_LEVEL,
- name = name,
integration_key = integration_key,
+ name = name,
units = hass_state.unit_of_measurement or '%',
+ add_default_alarm = add_alarm_events,
)
elif entity_state_type == EntityStateType.LIGHT_LEVEL:
# HA's illuminance sensor reports lux ("lx") as the
diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.js
index 27fe507d..0fe457cb 100644
--- a/src/hi/static/js/main.js
+++ b/src/hi/static/js/main.js
@@ -59,6 +59,9 @@
setEntityStateValueSelect: function( valueFieldId, instanceName, instanceId ) {
return _setEntityStateValueSelect( valueFieldId, instanceName, instanceId );
},
+ setEventClauseValueOperatorWidget: function( operatorFieldId, valueFieldId ) {
+ return _setEventClauseValueOperatorWidget( operatorFieldId, valueFieldId );
+ },
getScreenCenterPoint: function( element ) {
return _getScreenCenterPoint( element );
},
@@ -217,6 +220,28 @@
}
}
+ function _setEventClauseValueOperatorWidget( operatorFieldId, valueFieldId ) {
+ // EventClause operator change handler. For non-EQ operators
+ // (LT / LTE / GT / GTE) the value is a numeric threshold —
+ // swap the value field to a number input so users can enter
+ // one even when the entity_state has discrete choices. EQ
+ // leaves the existing widget alone; the entity_state-driven
+ // choice swap is the authoritative source for that case.
+ const op = $(`#${operatorFieldId}`).val().toLowerCase();
+ if (op === 'eq') {
+ return;
+ }
+ const valueElement = $(`#${valueFieldId}`);
+ const currentValue = valueElement.val();
+ const numericInput = $('<input>')
+ .attr( 'type', 'number' )
+ .attr( 'step', 'any' )
+ .attr( 'id', valueElement.attr('id') )
+ .attr( 'name', valueElement.attr('name') )
+ .val( currentValue );
+ valueElement.replaceWith( numericInput );
+ }
+
function _setEntityStateValueSelect( valueFieldId, instanceName, instanceId ) {
$.ajax({
type: 'GET',