I find this quite useful when quickly filtering entities by their origin.
eg. a class that creates one or more “virtual” sensors.
import inspect
from datetime import timedelta, datetime, tzinfo, time
async def get_class_filename(self):
return inspect.getfile(type(self))
async def create_or_update_sensor(self, virtual_sensor_name, friendly_name = None, value = None, icon = None, unit_of_measurement = None, device_class = None, entity = None, append_attributes = None):
class_filename = await self.get_class_filename()
final_attribs={
"created_by": class_filename,
"last_changed": datetime.now().replace(microsecond=0).isoformat()
}
# we can even append more attribs
if not device_class is None:
final_attribs["device_class"] = device_class
if not friendly_name is None:
final_attribs["friendly_name"] = friendly_name
if not entity is None:
final_attribs["entity_id"] = entity
if not icon is None:
final_attribs["icon"] = icon
if not unit_of_measurement is None:
final_attribs["unit_of_measurement"] = unit_of_measurement
if not append_attributes is None:
for key in append_attributes.keys():
final_attribs[key] = append_attributes[key]
await self.set_state(virtual_sensor_name, state=value, attributes=final_attribs)