Skip to content

Home Information - Your home, your data, organized.

Python

Fixed HAss integration and simulation for light/switch duality.

Anthony Cassandraef43431bb507
diff --git a/src/hi/apps/monitor/periodic_monitor.py b/src/hi/apps/monitor/periodic_monitor.py
index dccbde06..3ab43785 100644
--- a/src/hi/apps/monitor/periodic_monitor.py
+++ b/src/hi/apps/monitor/periodic_monitor.py
@@ -8,8 +8,6 @@ class PeriodicMonitor:
and periodically updated from some external source.
"""
- TRACE = True
-
def __init__( self, id: str, interval_secs: int ) -> None:
self._id = id
self._query_interval_secs = interval_secs
@@ -56,8 +54,7 @@ class PeriodicMonitor:
async def run_query(self) -> None:
self._query_counter += 1
- if self.TRACE:
- self._logger.debug(f"Running query {self._query_counter} for {self.__class__.__name__}")
+ self._logger.debug(f"Running query {self._query_counter} for {self.__class__.__name__}")
try:
await self.do_work()
except Exception as e:
diff --git a/src/hi/services/hass/hass_client.py b/src/hi/services/hass/hass_client.py
index a87a00bc..4da5a410 100644
--- a/src/hi/services/hass/hass_client.py
+++ b/src/hi/services/hass/hass_client.py
@@ -16,8 +16,6 @@ class HassClient:
API_BASE_URL = 'api_base_url'
API_TOKEN = 'api_token'
- TRACE = True
-
def __init__( self, api_options : Dict[ str, str ] ):
self._api_base_url = api_options.get( self.API_BASE_URL )
@@ -39,8 +37,7 @@ class HassClient:
url = f'{self._api_base_url}/api/states'
response = get( url, headers = self._headers )
data = json.loads(response.text)
- if self.TRACE:
- logger.debug( f'HAss Response = {response.text}' )
+ logger.debug( f'HAss Response = {response.text}' )
return [ HassConverter.create_hass_state(x) for x in data ]
def set_state( self, entity_id: str, state: str, attributes: dict = None ) -> dict:
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index 307b1898..59854c9f 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -381,21 +381,20 @@ class HassConverter:
# Observations:
#
- # - Some light switches have both a 'switch' and 'light' HAss state.
- # - Some light switches only have 'switch' HAss state.
- # - Some light switches only have 'light' HAss state.
+ # - Some insteon light switches have both a 'switch' and 'light'
+ # HAss state. These are just one actualy device state but HAss
+ # create duplicates to allow the switch to be treated as a
+ # "light" or something else if it is controlling something
+ # else. Thus, this is a HAss-internal artifact and not an
+ # instrinsic state of the device.
#
- # In Home Assistant, a "switch" is a simple on/off device, while a
- # "light" can have more advanced feature like dimming. An insteon
- # device reports it capabilities and some insteon devices are dual
- # mode and can support either. Thus, if a device is both a light
- # and switch, either can be used, thought they are operating on the
- # same underlying state.
+ # - Some light switches only have 'light' HAss state. e.g., Dimmers
#
# To deal with this, we have a special case so that we only create
- # one underlying EntityState for the two different HAss
+ # one underlying EntityState and Sensor for the two different HAss
# perspectives. A HassState is really the equivalent of a Sensor
- # in our data model.
+ # in our data model and we do not need the duplicates that are just
+ # a HAss-specific need.
prefix_to_entity_state = dict()
for hass_state in hass_state_list:
@@ -403,31 +402,19 @@ class HassConverter:
if (( hass_state.entity_id_prefix == HassApi.SWITCH_ID_PREFIX )
and ( HassApi.LIGHT_ID_PREFIX in prefix_to_entity_state )):
- existing_entity_state = prefix_to_entity_state[HassApi.LIGHT_ID_PREFIX]
+ continue
elif (( hass_state.entity_id_prefix == HassApi.LIGHT_ID_PREFIX )
and ( HassApi.SWITCH_ID_PREFIX in prefix_to_entity_state )):
- existing_entity_state = prefix_to_entity_state[HassApi.SWITCH_ID_PREFIX]
-
- else:
- existing_entity_state = None
-
- if existing_entity_state:
- HiModelHelper.add_on_off_controller(
- entity = entity,
- entity_state = existing_entity_state,
- integration_key = state_integration_key,
- name = hass_state.friendly_name,
- )
- else:
- entity_state = cls._create_hass_state_sensor_or_controller(
- hass_device = hass_device,
- hass_state = hass_state,
- entity = entity,
- integration_key = state_integration_key,
- add_alarm_events = add_alarm_events,
- )
+ continue
+ entity_state = cls._create_hass_state_sensor_or_controller(
+ hass_device = hass_device,
+ hass_state = hass_state,
+ entity = entity,
+ integration_key = state_integration_key,
+ add_alarm_events = add_alarm_events,
+ )
prefix_to_entity_state[hass_state.entity_id_prefix] = entity_state
continue
return
diff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.py
index 0676520b..cf23bfc6 100644
--- a/src/hi/services/hass/monitors.py
+++ b/src/hi/services/hass/monitors.py
@@ -39,9 +39,7 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):
await self._initialize()
id_to_hass_state_map = self.hass_manager().fetch_hass_states_from_api( verbose = False )
-
- if self.TRACE:
- logger.debug( f'Fetched {len(id_to_hass_state_map)} HAss States' )
+ logger.debug( f'Fetched {len(id_to_hass_state_map)} HAss States' )
current_datetime = datetimeproxy.now()
sensor_response_latest_map = dict()
diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.py
index 5da7931c..2437c9b4 100644
--- a/src/hi/services/zoneminder/monitors.py
+++ b/src/hi/services/zoneminder/monitors.py
@@ -23,7 +23,6 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
ZONEMINDER_SERVER_TIMEZONE = 'America/Chicago'
ZONEMINDER_POLLING_INTERVAL_SECS = 10
- TRACE = False
CACHING_DISABLED = True
def __init__( self ):
@@ -86,8 +85,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
'tz': self._zm_tzname,
}
events = self.zm_manager().get_zm_events( options = options )
- if self.TRACE:
- logger.debug( f'Found {len(events)} new ZM events' )
+ logger.debug( f'Found {len(events)} new ZM events' )
# Sensor readings and state value transitions are points in time,
# but ZoneMinder events are intervals. Thus, one ZoneMinder event
@@ -108,8 +106,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
closed_zm_event_list = list()
zm_monitor_ids_seen = set()
for zm_api_event in events:
- if self.TRACE:
- logger.debug( f'ZM Api Event: {zm_api_event.get()}' )
+ logger.debug( f'ZM Api Event: {zm_api_event.get()}' )
zm_event = ZmEvent( zm_api_event = zm_api_event,
zm_tzname = self._zm_tzname )
diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.py
index 2e6af913..1798dd42 100644
--- a/src/hi/services/zoneminder/zm_manager.py
+++ b/src/hi/services/zoneminder/zm_manager.py
@@ -28,8 +28,6 @@ class ZoneMinderManager( Singleton ):
ZM Api code: https://github.com/ZoneMinder/zoneminder/tree/master/web/api/app/Controller
PyZM code: https://github.com/pliablepixels/pyzm/tree/357fdbd1937dab8027882598b61258ef43dc366a
"""
- TRACE = False
-
ZM_ENTITY_NAME = 'ZoneMinder'
ZM_SYSTEM_INTEGRATION_NAME = 'system'
ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'
@@ -186,8 +184,7 @@ class ZoneMinderManager( Singleton ):
or ( state_list_age.seconds > self.STATE_REFRESH_INTERVAL_SECS )):
self._zm_state_list = self.zm_client.states().list()
self._zm_state_timestamp = datetimeproxy.now()
- if self.TRACE:
- logger.debug( f'Fetched ZM states: {[ x.get() for x in self._zm_state_list ]}' )
+ logger.debug( f'Fetched ZM states: {[ x.get() for x in self._zm_state_list ]}' )
return self._zm_state_list
def get_zm_monitors( self, force_load : bool = False ) -> List[ ZmMonitor ]:
@@ -200,8 +197,7 @@ class ZoneMinderManager( Singleton ):
}
self._zm_monitor_list = self.zm_client.monitors( options ).list()
self._zm_monitor_timestamp = datetimeproxy.now()
- if self.TRACE:
- logger.debug( f'\n\nFetched ZM monitors: {[ x.get() for x in self._zm_monitor_list ]}\n\n' )
+ logger.debug( f'\n\nFetched ZM monitors: {[ x.get() for x in self._zm_monitor_list ]}\n\n' )
return self._zm_monitor_list
diff --git a/src/hi/settings/development.py b/src/hi/settings/development.py
index 06e182d2..e13bf64a 100644
--- a/src/hi/settings/development.py
+++ b/src/hi/settings/development.py
@@ -122,6 +122,34 @@ LOGGING = {
'handlers': ['console' ],
'level': 'DEBUG',
},
+ 'hi.apps.alert': {
+ 'handlers': ['console' ],
+ 'level': 'INFO',
+ },
+ 'hi.apps.sense': {
+ 'handlers': ['console' ],
+ 'level': 'INFO',
+ },
+ 'hi.apps.control': {
+ 'handlers': ['console' ],
+ 'level': 'INFO',
+ },
+ 'hi.apps.notify': {
+ 'handlers': ['console' ],
+ 'level': 'INFO',
+ },
+ 'hi.apps.monitor': {
+ 'handlers': ['console' ],
+ 'level': 'INFO',
+ },
+ 'hi.services.hass': {
+ 'handlers': ['console' ],
+ 'level': 'INFO',
+ },
+ 'hi.services.zoneminder': {
+ 'handlers': ['console' ],
+ 'level': 'INFO',
+ },
},
}
diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.py
index face950a..05804899 100644
--- a/src/hi/simulator/services/hass/sim_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -119,12 +119,17 @@ class HassInsteonLightSwitchState( HassInsteonState ):
"insteon_address": self.insteon_address,
"insteon_group": 1,
}
+
+@dataclass( frozen = True )
+class HassInsteonDimmerLightSwitchFields( HassInsteonSimEntityFields ):
+ pass
+
@dataclass
-class HassInsteonLightLightState( HassInsteonState ):
+class HassInsteonDimmerLightLightState( HassInsteonState ):
- sim_entity_fields : HassInsteonLightSwitchFields
+ sim_entity_fields : HassInsteonDimmerLightSwitchFields
sim_state_type : SimStateType = SimStateType.ON_OFF
sim_state_id : str = 'light'
@@ -134,34 +139,32 @@ class HassInsteonLightLightState( HassInsteonState ):
@property
def entity_id(self):
- return 'light.switchlinc_relay_%s' % self.insteon_address.replace( '.', '_' )
+ return 'light.switchlinc_dimmer_%s' % self.insteon_address.replace( '.', '_' )
@property
def attributes(self) -> Dict[ str, str ]:
return {
- 'color_mode': 'onoff',
'friendly_name': self.entity_name,
- 'supported_color_modes': [
- 'onoff',
- ],
- 'supported_features': 0,
+ "icon": "mdi:lightbulb",
+ "insteon_address": self.insteon_address,
+ "insteon_group": 1,
}
-@dataclass
-class HassInsteonDualBandLightSwitchState( HassInsteonLightSwitchState ):
-
- @property
- def entity_id(self):
- return 'switch.switchlinc_relay_dual_band_%s' % self.insteon_address.replace( '.', '_' )
+@dataclass( frozen = True )
+class HassInsteonDualBandLightSwitchFields( HassInsteonLightSwitchFields ):
+ pass
@dataclass
-class HassInsteonDualBandLightLightState( HassInsteonLightLightState ):
+class HassInsteonDualBandLightSwitchState( HassInsteonLightSwitchState ):
+ """Dual-band variant (can use powerline or RF) """
+
+ sim_entity_fields : HassInsteonDualBandLightSwitchFields
@property
def entity_id(self):
- return 'light.switchlinc_relay_dual_band_%s' % self.insteon_address.replace( '.', '_' )
+ return 'switch.switchlinc_relay_dual_band_%s' % self.insteon_address.replace( '.', '_' )
@dataclass( frozen = True )
@@ -279,23 +282,65 @@ class HassInsteonOpenCloseSensorState( HassInsteonState ):
}
+@dataclass( frozen = True )
+class HassInsteonOutletFields( HassInsteonSimEntityFields ):
+ pass
+
+
+@dataclass
+class HassInsteonOutletState( HassInsteonState ):
+
+ sim_entity_fields : HassInsteonOutletFields
+ sim_state_type : SimStateType = SimStateType.ON_OFF
+ sim_state_id : str = 'outlet'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Outlet'
+
+ @property
+ def entity_id(self):
+ return 'switch.outletlinc_relay_%s' % self.insteon_address.replace( '.', '_' )
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return {
+ 'device_class': 'outlet',
+ 'friendly_name': self.entity_name,
+ "insteon_address": self.insteon_address,
+ "insteon_group": 1,
+ }
+
+
HASS_SIM_ENTITY_DEFINITION_LIST = [
SimEntityDefinition(
- class_label = 'Insteon Light Switch',
+ class_label = 'Insteon Switch',
sim_entity_type = SimEntityType.LIGHT,
sim_entity_fields_class = HassInsteonLightSwitchFields,
sim_state_class_list = [
+ # HAss create duplicate states "switch" and "light" since a
+ # switch may be use for a light or something else. We only need
+ # one of these since there is only one underlying state.
HassInsteonLightSwitchState,
- HassInsteonLightLightState,
],
),
SimEntityDefinition(
- class_label = 'Insteon Light Switch (dual band)',
+ class_label = 'Insteon Light Switch (dimmer)',
sim_entity_type = SimEntityType.LIGHT,
- sim_entity_fields_class = HassInsteonLightSwitchFields,
+ sim_entity_fields_class = HassInsteonDimmerLightSwitchFields,
sim_state_class_list = [
+ HassInsteonDimmerLightLightState,
+ ],
+ ),
+ SimEntityDefinition(
+ class_label = 'Insteon Switch (dual band)',
+ sim_entity_type = SimEntityType.LIGHT,
+ sim_entity_fields_class = HassInsteonDualBandLightSwitchFields,
+ sim_state_class_list = [
+ # HAss create duplicate states "switch" and "light" since a
+ # switch may be use for a light or something else. We only need
+ # one of these since there is only one underlying state.
HassInsteonDualBandLightSwitchState,
- HassInsteonDualBandLightLightState,
],
),
SimEntityDefinition(
@@ -309,11 +354,19 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [
],
),
SimEntityDefinition(
- class_label = 'Insteon Open/Close Sensor',
+ class_label = 'Insteon Open/Close Detector',
sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,
sim_entity_fields_class = HassInsteonOpenCloseSensorFields,
sim_state_class_list = [
HassInsteonOpenCloseSensorState,
],
),
+ SimEntityDefinition(
+ class_label = 'Insteon Outlet',
+ sim_entity_type = SimEntityType.ELECTRICAL_OUTLET,
+ sim_entity_fields_class = HassInsteonOutletFields,
+ sim_state_class_list = [
+ HassInsteonOutletState,
+ ],
+ ),
]
diff --git a/src/hi/simulator/simulator.py b/src/hi/simulator/simulator.py
index 9cbf03f9..ef47cc66 100644
--- a/src/hi/simulator/simulator.py
+++ b/src/hi/simulator/simulator.py
@@ -8,12 +8,48 @@ from .sim_entity import SimEntity
class Simulator( Singleton ):
"""
- The class that each simulator should subclass and include in a
- simulator.py file in its app directory. This is how the
- SimulatorManager discovers the types of simulator entities and states
- provided by the simulator. This is also used by the simulators to get
- the current satte of which entities, states and state values currently
- are defined.
+ Defining a Simulator
+
+ - Each simulator should subclass this in a file named "simulator.py" in
+ its app directory.
+
+ - The simulator's app directory should be located in the "simulator/services"
+ subdirectory.
+
+ - The SimulatorManager will auto-discovery all simulators with a
+ simulator.py file in that services directopry.
+
+ - The simulator should also define a urls.py and views.py file with the
+ needed API endpoints.
+
+ - The urls.py will also be auto-discovered by logic in the
+ simulator/urls.py file
+
+ Responsibilities
+
+ - A simulator must provide a list of SimEntityDefinition instances via
+ overriding the sim_entity_definition_list() method. This tells the
+ simulator the available types of simulator entities that are
+ available to be defined, what extra custrom fields it needs and the
+ list of SimState types the entity contains.
+
+ - SimState instances is what the simulator UI shows as manually
+ adjustable. The API views of the simulator should convert those
+ entities and current state values into the proper API responses.
+
+ - The SimulatorManager is responsible for creating SimEntity instances
+ and for updating the values of then SimState instances.
+
+ - SimEntity definitions are persisted in the database with DbSimEntity,
+ but ther SimState definitions and values are not persisted. e.g., A
+ simulator server restart will lose any current SimState values.
+
+ - The SimulatorManager also supports defining and switching between
+ different simulation profiles, each with its own set of SimEntity
+ definitions. The individual simulator subclasses do not need to be
+ aware of this as the SimulatorManager creates a new simulator
+ subclass instance for each profile.
+
"""
def __init_singleton__( self ):