Skip to content

Commit

Permalink
Merge pull request #1 from hudsonbrendon/develop
Browse files Browse the repository at this point in the history
Refatora o componente
  • Loading branch information
hudsonbrendon authored Jun 23, 2021
2 parents 56a682e + 6b086ce commit 449e917
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 93 deletions.
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"files.associations": {
"*.yaml": "home-assistant"
}
}
3 changes: 2 additions & 1 deletion custom_components/clarotv/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
"documentation": "https://github.com/hudsonbrendon/sensor.claro.com.br",
"dependencies": [],
"codeowners": ["@hudsonbrendon"],
"requirements": []
"requirements": [],
"iot_class": "local_polling"
}
188 changes: 96 additions & 92 deletions custom_components/clarotv/sensor.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,36 @@
"""
A platform that provides information about programation on claro tv.
For more details on this component, refer to the documentation at
https://github.com/hudsonbrendon/sensor.clarotv
"""
import json
import logging
import string
from collections import defaultdict
from datetime import datetime, timedelta

import async_timeout
import homeassistant.helpers.config_validation as cv
import pytz
import requests
import voluptuous as vol
from dateutil.relativedelta import relativedelta
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from homeassistant.helpers.entity import Entity
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_NAME,
CONF_RESOURCES,
STATE_UNKNOWN,
)
from homeassistant.util import Throttle

_LOGGER = logging.getLogger(__name__)

ICON = "mdi:television-classic"

SCAN_INTERVAL = timedelta(seconds=60)

ATTRIBUTION = "Data provided by clarotv api"

DOMAIN = "clarotv"

CONF_CHANNEL_ID = "channel_id"
CONF_CHANNEL_NAME = "channel_name"
CONF_CHANNEL_LOGO = "channel_logo"
SCAN_INTERVAL = timedelta(minutes=10)

ICON = "mdi:video"

BASE_URL = "https://programacao.claro.com.br/gatekeeper/exibicao/select?q=id_cidade:1&wt=json&sort=dh_inicio%20asc&fl=dh_inicio%20st_titulo%20titulo%20id_programa%20id_exibicao&fq=dh_inicio:%5B{}%20TO%20{}%5D&fq=id_canal:{}"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
Expand All @@ -33,107 +40,104 @@
}
)

_LOGGER = logging.getLogger(__name__)
BASE_URL = "https://programacao.claro.com.br/gatekeeper/exibicao/select?q=id_cidade:1&wt=json&sort=dh_inicio%20asc&fl=dh_inicio%20st_titulo%20titulo%20id_programa%20id_exibicao&fq=dh_inicio:%5B{}%20TO%20{}%5D&fq=id_canal:{}"


async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Setup sensor platform."""
def get_data(channel_id, channel_name, channel_logo):
"""Get The request from the api"""
first_date = datetime.now(pytz.timezone("America/Sao_Paulo"))
second_date = first_date + relativedelta(months=1)
programations = []
url = BASE_URL.format(
first_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
second_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
channel_id,
)
response = requests.get(url)
if response.ok:
programations.append(
{
"title_default": "$title",
"line1_default": "",
"line2_default": "$release",
"line3_default": "$runtime",
"line4_default": channel_name,
"icon": "mdi:arrow-down-bold",
}
)

for programation in response.json().get("response").get("docs"):
programations.append(
dict(
title=programation["titulo"],
poster=channel_logo,
fanart=channel_logo,
runtime=programation["dh_inicio"].split("T")[1].split("Z")[0],
release=programation["dh_inicio"].split("T")[1].split("Z")[0],
airdate=programation["dh_inicio"].split("T")[1].split("Z")[0],
)
)

else:
_LOGGER.error("Cannot perform the request")
return programations


def setup_platform(hass, config, add_entities, discovery_info=None):
"""Setup the currency sensor"""

channel_id = config["channel_id"]
channel_name = config["channel_name"]
channel_logo = config["channel_logo"]
name = channel_name.capitalize()
session = async_create_clientsession(hass)
async_add_entities(
[ClaroTVSensor(channel_id, channel_name, channel_logo, name, session)], True
)

add_entities(
[
ClaroTVSensor(
hass, name, channel_id, channel_name, channel_logo, SCAN_INTERVAL
)
],
True,
)

class ClaroTVSensor(Entity):
"""claro.com.br Sensor class"""

def __init__(self, channel_id, channel_name, channel_logo, name, session):
self._state = channel_name
class ClaroTVSensor(SensorEntity):
def __init__(self, hass, name, channel_id, channel_name, channel_logo, interval):
"""Inizialize sensor"""
self._state = STATE_UNKNOWN
self._hass = hass
self.interval = interval
self._channel_id = channel_id
self._channel_name = channel_name
self._channel_logo = channel_logo
self.session = session
self._name = name
self._programations = []

async def async_update(self):
"""Update sensor."""
_LOGGER.debug("%s - Running update", self._name)
first_date = datetime.now(pytz.timezone("America/Sao_Paulo"))
second_date = first_date + relativedelta(months=1)
try:
url = BASE_URL.format(
first_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
second_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
self._channel_id,
)
async with async_timeout.timeout(10, loop=self.hass.loop):
response = await self.session.get(url)
programations = await response.json()

self._programations.append(
{
"title_default": "$title",
"line1_default": "",
"line2_default": "$release",
"line3_default": "$runtime",
"line4_default": self._channel_name,
"icon": "mdi:arrow-down-bold",
}
)

for programation in programations.get("response").get("docs"):
self._programations.append(
dict(
title=programation["titulo"],
poster=self._channel_logo,
fanart=self._channel_logo,
runtime=programation["dh_inicio"]
.split("T")[1]
.split("Z")[0],
release=programation["dh_inicio"]
.split("T")[1]
.split("Z")[0],
airdate=programation["dh_inicio"]
.split("T")[1]
.split("Z")[0],
)
)

except Exception as error:
_LOGGER.debug("%s - Could not update - %s", self._name, error)

@property
def name(self):
"""Name."""
"""Return the name sensor"""
return self._name

@property
def state(self):
"""State."""
return self._state
def icon(self):
"""Return the default icon"""
return ICON

@property
def programations(self):
"""Programations."""
return [
i
for n, i in enumerate(self._programations)
if i not in self._programations[n + 1 :]
]
def state(self):
"""Return the state of the sensor"""
now = datetime.now(pytz.timezone("America/Sao_Paulo"))
return now.strftime("%d-%m-%Y %H:%M:%S")

@property
def icon(self):
"""Icon."""
return ICON
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""
return {ATTR_ATTRIBUTION: ATTRIBUTION}

@property
def device_state_attributes(self):
"""Attributes."""
return {
"data": self._programations,
}
return {"data": Throttle(self.interval)(self.update)}

def update(self):
"""Get the latest update fron the api"""
return get_data(self._channel_id, self._channel_name, self._channel_logo)

0 comments on commit 449e917

Please sign in to comment.