|
| 1 | +"""A Python Client to interact with Dingz devices.""" |
| 2 | +import asyncio |
| 3 | +import logging |
| 4 | + |
| 5 | +import aiohttp |
| 6 | +import async_timeout |
| 7 | + |
| 8 | +from . import exceptions |
| 9 | +from .constants import TEMPERATURE, MOTION, LIGHT, PUCK, INFO |
| 10 | + |
| 11 | +_LOGGER = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class Dingz: |
| 15 | + """A class for handling the communication with a Dingz device.""" |
| 16 | + |
| 17 | + def __init__(self, device, loop, session): |
| 18 | + """Initialize the connection.""" |
| 19 | + self._loop = loop |
| 20 | + self._session = session |
| 21 | + self.token = None |
| 22 | + self.device = device |
| 23 | + self.data = None |
| 24 | + |
| 25 | + async def get_data(self, endpoint): |
| 26 | + """Retrieve the data from a given endpoint.""" |
| 27 | + try: |
| 28 | + with async_timeout.timeout(5, loop=self._loop): |
| 29 | + response = await self._session.get(f"{endpoint}") |
| 30 | + |
| 31 | + _LOGGER.debug("Response from Dingz device: %s", response.status) |
| 32 | + self.data = await response.json() |
| 33 | + _LOGGER.debug(self.data) |
| 34 | + except (asyncio.TimeoutError, aiohttp.ClientError): |
| 35 | + _LOGGER.error("Can not load data from Dingz device") |
| 36 | + self.data = None |
| 37 | + raise exceptions.DingzConnectionError() |
| 38 | + |
| 39 | + @property |
| 40 | + def info(self): |
| 41 | + """Get the state of the motion sensor.""" |
| 42 | + data = await self.get_data(INFO) |
| 43 | + return data['motion'] |
| 44 | + |
| 45 | + @property |
| 46 | + def puck(self): |
| 47 | + """Get the state of the hardware.""" |
| 48 | + data = await self.get_data(PUCK) |
| 49 | + if self.data is not None: |
| 50 | + return {'firmware': data['fw']['version'], 'hardware': data['hw']['version']} |
| 51 | + |
| 52 | + @property |
| 53 | + def temperature(self): |
| 54 | + """Get the temperature.""" |
| 55 | + data = await self.get_data(TEMPERATURE) |
| 56 | + return round(data['temperature'], 2) |
| 57 | + |
| 58 | + @property |
| 59 | + def light(self): |
| 60 | + """Get the brightness.""" |
| 61 | + data = await self.get_data(LIGHT) |
| 62 | + return round(data['intensity'], 2) |
| 63 | + |
| 64 | + @property |
| 65 | + def day(self): |
| 66 | + """Get the state if daytime or not.""" |
| 67 | + data = await self.get_data(LIGHT) |
| 68 | + return data['day'] |
| 69 | + |
| 70 | + @property |
| 71 | + def motion(self): |
| 72 | + """Get the state of the motion sensor.""" |
| 73 | + data = await self.get_data(MOTION) |
| 74 | + return data['motion'] |
| 75 | + |
| 76 | + |
| 77 | + |
0 commit comments