Skip to content

Commit

Permalink
Added coordinator
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabriel Wieskamp committed Feb 9, 2024
1 parent 12d6b52 commit ea39b9f
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 67 deletions.
11 changes: 10 additions & 1 deletion custom_components/glentronics/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
from homeassistant.const import Platform
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady

from .const import PLATFORMS
from .const import DOMAIN
from .coordinator import GlentronicsCoordinator

PLATFORMS = [
Platform.BINARY_SENSOR
]

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
coordinator = GlentronicsCoordinator(hass, entry)
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

return True
Expand Down
86 changes: 28 additions & 58 deletions custom_components/glentronics/binary_sensor.py
Original file line number Diff line number Diff line change
@@ -1,70 +1,35 @@
import websockets
import aiohttp
import json
import pydash
from homeassistant.helpers.entity import Entity, DeviceInfo
from homeassistant.components.binary_sensor import BinarySensorDeviceClass
from homeassistant.const import CONF_USERNAME, CONF_PIN
from .const import DOMAIN, URL, _LOGGER, API_USERNAME, API_PASSWORD, BINARY_SENSORS
from .const import DOMAIN, _LOGGER, BINARY_SENSORS

async def async_setup_entry(hass, config, async_add_entities) -> None:
creds = {
"APIUsername": API_USERNAME,
"APIPassword": API_PASSWORD,
"ProxyID": config.data[CONF_PIN],
"Username": config.data[CONF_USERNAME]
}

url = URL + "/Device/RetrieveProxyStatus"
async with aiohttp.ClientSession() as session:
async with session.post(url,data=creds) as r:
results = await r.json()
device = []
device.append(pydash.get(results,"Location"))
device.append(pydash.get(results,"StatusList.0.ControlUnitType"))
fields = pydash.get(results,"StatusFields")
async def async_setup_entry(hass, config, async_add_entities):

coordinator = hass.data[DOMAIN][config.entry_id]
entities = []
for idx, field in enumerate(fields):
entities.append(GlentronicsSensor(hass, creds, device, field, idx))

for field in BINARY_SENSORS:
entities.append(GlentronicsSensor(coordinator, field, BINARY_SENSORS[field]))
async_add_entities(entities)

class GlentronicsSensor(Entity):

def parse_results(self,results):
state = pydash.get(results,f"{self.idx}.FieldStatusOK")
if bool(state):
if not self.field.find("WiFi") == 0:
self._state = "off"
else:
self._state = "on"
else:
self._state = "off"
self._attributes["Value"] = pydash.get(results,f"{self.idx}.FieldValue")
self._attributes["Detail"] = pydash.get(results,f"{self.idx}.FieldDetailInfo")
self._attributes["Warning"] = pydash.get(results,f"{self.idx}.IsWarning")

def __init__(self,hass,creds,device,field, idx):
self.creds = creds
self.device = device[0]
def __init__(self,coordinator,idx,entity):
self.coordinator = coordinator
self.entity = entity
self.idx = idx
label = field["FieldLabel"]
loc=label.find("(")
if loc == -1:
loc=None
self.field = label[0:loc].strip()
self.device = self.coordinator.device[0]
self.field = entity.name
self._unique_id = f"{DOMAIN}_{self.device}_{self.field}"
self._name = f"{self.device}_{self.field}"
self._icon = BINARY_SENSORS[self.field].icon
self._device_class = BINARY_SENSORS[self.field].device_class
self._icon = entity.icon
self._device_class = entity.device_class
self._state = None
self._attributes = {}
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device[0])},
identifiers={(DOMAIN, self.device)},
manufacturer=DOMAIN,
model=device[1],
name=device[0].capitalize())
model=self.coordinator.device[1],
name=self.device.capitalize())

@property
def unique_id(self):
Expand All @@ -91,12 +56,17 @@ def state_attributes(self):
return self._attributes

async def async_update(self) -> None:
try:
url = URL + "/Device/RetrieveProxyStatus"
async with aiohttp.ClientSession() as session:
async with session.post(url,data=self.creds) as r:
results = await r.json()
except:
_LOGGER.error("Failed to communicate to the API")

self.parse_results(pydash.get(results,"StatusFields"))
for field in self.coordinator.fields:
if pydash.get(field,"FieldLabel").find(self.idx) == 0:
state = pydash.get(field,"FieldStatusOK")
self._attributes["Value"] = pydash.get(field,"FieldValue")
self._attributes["Detail"] = pydash.get(field,"FieldDetailInfo")
self._attributes["Warning"] = pydash.get(field,"IsWarning")
if bool(state):
if not self.field.find("WiFi") == 0:
self._state = "off"
else:
self._state = "on"
else:
self._state = "off"
7 changes: 3 additions & 4 deletions custom_components/glentronics/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_PIN, CONF_USERNAME, CONF_PASSWORD
from .exceptions import ApiException, AuthenticationError
from .const import DOMAIN, URL, _LOGGER, API_USERNAME, API_PASSWORD
from .const import DOMAIN, _LOGGER, LOGIN_URL, API_URL, API_USERNAME, API_PASSWORD

DATA_SCHEMA = vol.Schema(
{
Expand All @@ -23,9 +23,8 @@ async def validate_input(hass: core.HomeAssistant, data):
"email": data[CONF_USERNAME],
"Password": data[CONF_PASSWORD]
}
url= "https://glentronicsconnect.com/ApiAccount/Login"
async with aiohttp.ClientSession() as session:
async with session.post(url,data=creds) as r:
async with session.post(LOGIN_URL,data=creds) as r:
status = r.status
except:
_LOGGER.error('Troubles talking to the API')
Expand All @@ -36,7 +35,7 @@ async def validate_input(hass: core.HomeAssistant, data):
"APIPassword": API_PASSWORD,
"Username": data[CONF_USERNAME]
}
url = URL + "/Device/RetrieveWifiModules"
url = API_URL + "/Device/RetrieveWifiModules"
async with aiohttp.ClientSession() as session:
async with session.post(url,data=creds) as r:
results = await r.json()
Expand Down
10 changes: 7 additions & 3 deletions custom_components/glentronics/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@

DOMAIN = "glentronics"

ICON = 'mdi:pipe'
COORDINATOR = "coordinator"

HOST = "api.glentronicsconnect.com"
URL = f"https://{HOST}"
# In Seconds
UPDATE_FREQ = 30

LOGIN_URL = "https://glentronicsconnect.com/ApiAccount/Login"
API_URL = "https://api.glentronicsconnect.com"
API_USERNAME = "Glentronics"
API_PASSWORD = "API201622@"

PLATFORMS = [Platform.BINARY_SENSOR]

BINARY_SENSORS = {
"Alarm Status": BinarySensorEntityDescription(
name="Status",
Expand Down
2 changes: 1 addition & 1 deletion custom_components/glentronics/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"issue_tracker": "https://github.com/theOrakle/glentronics/issues",
"loggers": ["custom_components.glentronics"],
"requirements": ["pydash"],
"version": "0.1.4",
"version": "0.1.5",
"dependencies": [],
"codeowners": ["@theOrakle"]
}

0 comments on commit ea39b9f

Please sign in to comment.