Skip to content

Commit

Permalink
Added Sensors (initial try)
Browse files Browse the repository at this point in the history
  • Loading branch information
blueflame66 committed May 22, 2023
1 parent f2e443a commit cabedb2
Show file tree
Hide file tree
Showing 3 changed files with 183 additions and 10 deletions.
9 changes: 7 additions & 2 deletions custom_components/ownerrez/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@

_LOGGER = logging.getLogger(__name__)
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=7200)
PLATFORMS: list[Platform] = [Platform.CALENDAR]
# PLATFORMS: list[Platform] = [Platform.CALENDAR]
PLATFORMS = ["sensor", "calendar"]


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
Expand Down Expand Up @@ -87,7 +88,7 @@ def __init__(self, config, orproperty):
self.tzid = orproperty["TimeZoneId"]
self.name = orproperty["Name"]
self.orid = orproperty["Id"]
self.auth = auth = aiohttp.BasicAuth(
self.auth = aiohttp.BasicAuth(
config.get(CONF_USERNAME), config.get(CONF_API_TOKEN)
)
self.calendar = []
Expand Down Expand Up @@ -207,6 +208,10 @@ async def update(self):
+ guest_name["last_name"]
+ " TZ:"
+ tz.zone,
"guestname": guest_name["first_name"]
+ " "
+ guest_name["last_name"],
"orid": self.orid,
}
self.calendar.append(new_record)
await session.close()
13 changes: 5 additions & 8 deletions custom_components/ownerrez/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

import copy
import logging
import aiohttp
import pytz

from .const import DEFAULT_URL
# import aiohttp
# import pytz

# from .const import DEFAULT_URL
from homeassistant.util import dt
from datetime import datetime, timedelta, date

Expand Down Expand Up @@ -44,8 +45,6 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
ENTITY_ID_FORMAT, DOMAIN + "_" + str(orCal.orid), hass=hass
)

# cal_events = hass.data[DOMAIN][jre3["Key"]]

calendar = ORCalendar(entity_id, orCal)

async_add_entities([calendar], True)
Expand Down Expand Up @@ -90,11 +89,9 @@ async def async_get_events(self, hass, start_date, end_date):
# )

async def async_update(self):
"""Glenn"""
"""Update the Calendar"""
_LOGGER.debug("Running ICalCalendarEventDevice async update for %s", self.name)
await self.cal_events.update()
j = self.name
k = self.cal_events
event = copy.deepcopy(self.cal_events.event)
if event is None:
self._event = event
Expand Down
171 changes: 171 additions & 0 deletions custom_components/ownerrez/sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
"""Creating sensors for upcoming events."""


from datetime import datetime, timedelta
import logging


from homeassistant.const import CONF_NAME
from homeassistant.helpers.entity import Entity, generate_entity_id

# from homeassistant.components.sensor import CalendarEvent

from .const import CONF_MAX_EVENTS, DOMAIN

_LOGGER = logging.getLogger(__name__)


# async def async_setup_entry(hass, config, add_entities, discovery_info=None):
async def async_setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up this integration with config flow."""
return True


async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Sensors"""
config = config_entry.data
max_events = config.get(CONF_MAX_EVENTS) - 1

for orCal in hass.data[DOMAIN]["Calendars"]:
sensors = []
await orCal.update()

Glenn2 = orCal.calendar
Glenn3 = hass.data[DOMAIN]
for index, OR_Event in enumerate(orCal.calendar):
if index < max_events:
entity_id = generate_entity_id(
"sensor.{}",
DOMAIN + "_" + str(orCal.orid) + "_" + str(index),
hass=hass,
)
Glenn3 = OR_Sensor(hass, OR_Event, index, entity_id)
sensors.append(OR_Sensor(hass, OR_Event, index, entity_id))

async_add_entities(sensors)


# sensors = []
# for eventnumber in range(max_events):
# sensors.append(ICalSensor(hass, ical_events, DOMAIN + " " + name, eventnumber))

# async_add_entities(sensors)


# pylint: disable=too-few-public-methods
class OR_Sensor(Entity):
"""
Represents the Nth upcoming event.
May have a name like 'sensor.mycalander_event_0' for the first
upcoming event.
"""

def __init__(self, hass, OR_Event, index, entity_id):
"""
Initialize the sensor.
sensor_name is typically the name of the calendar.
eventnumber indicates which upcoming event this is, starting at zero
"""
self._event_number = index
self._hass = hass
# self.ical_events = ical_events
self._entity_id = entity_id
# self._unique_id = str(OR_Event["orid"]) + "_" + str(index)
self._event_attributes = {
"summary": "glenn",
"description": "moore",
"location": None,
"start": OR_Event["start"],
"end": OR_Event["end"],
"cleaning": None,
}
self._guestname = OR_Event["guestname"]
self._state = None
self._is_available = None

@property
def entity_id(self):
"""Return the entity_id of the sensor."""
return self._entity_id

@property
def index_no(self):
"""Return the entity_id of the sensor."""
return self._event_number

@property
def name(self):
"""Return the guest name for the Sensor."""
return self._guestname

@property
def icon(self):
"""Return the icon for the frontend."""
return "mdi:account-filter"

@property
def state(self):
"""Return the date of the next event."""
return self._state

@property
def extra_state_attributes(self):
"""Return the attributes of the event."""
return self._event_attributes

@property
def available(self):
"""Return True if ZoneMinder is available."""
return self.extra_state_attributes["start"] is not None

async def async_update(self):
"""Update the sensor."""
_LOGGER.debug("Running ICalSensor async update for %s", self.name)

"""
await self.ical_events.update()
event_list = self.ical_events.calendar
# _LOGGER.debug(f"Event List: {event_list}")
if event_list and (self._event_number < len(event_list)):
val = event_list[self._event_number]
name = val.get("summary", "Unknown")
start = val.get("start")
# _LOGGER.debug(f"Val: {val}")
_LOGGER.debug(
"Adding event %s - Start %s - End %s - as event %s to calendar %s",
val.get("summary", "unknown"),
val.get("start"),
val.get("end"),
str(self._event_number),
self.name,
)
self._event_attributes["summary"] = val.get("summary", "unknown")
self._event_attributes["start"] = val.get("start")
self._event_attributes["end"] = val.get("end")
self._event_attributes["location"] = val.get("location", "")
self._event_attributes["description"] = val.get("description", "")
self._event_attributes["eta"] = (
start - datetime.now(start.tzinfo) + timedelta(days=1)
).days
self._event_attributes["all_day"] = val.get("all_day")
self._state = f"{name} - {start.strftime('%-d %B %Y')}"
if not val.get("all_day"):
self._state += f" {start.strftime('%H:%M')}"
# self._is_available = True
elif self._event_number >= len(event_list):
# No further events are found in the calendar
self._event_attributes = {
"summary": None,
"description": None,
"location": None,
"start": None,
"end": None,
"eta": None,
}
self._state = None
self._is_available = None """

0 comments on commit cabedb2

Please sign in to comment.