Skip to content

Commit

Permalink
Dump websocket data
Browse files Browse the repository at this point in the history
  • Loading branch information
sebr committed Dec 28, 2019
1 parent 3450432 commit 500c24c
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 16 deletions.
58 changes: 52 additions & 6 deletions custom_components/bhyve/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Support for Orbit BHyve Service."""
"""Support for Ambient Weather Station Service."""
import logging
import os
import pprint

import voluptuous as vol

Expand All @@ -18,7 +20,15 @@
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_call_later

from .const import CONF_ATTRIBUTION, DOMAIN, MANUFACTURER, TOPIC_UPDATE
from .const import (
CONF_ATTRIBUTION,
CONF_CONF_DIR,
CONF_PACKET_DUMP,
CONF_WATERING_DURATION,
DOMAIN,
MANUFACTURER,
TOPIC_UPDATE,
)
from .pybhyve import Client
from .pybhyve.errors import WebsocketError

Expand All @@ -27,14 +37,22 @@
DATA_CONFIG = "config"

DEFAULT_SOCKET_MIN_RETRY = 15
DEFAULT_PACKET_DUMP = True
DEFAULT_CONF_DIR = ""
DEFAULT_WATCHDOG_SECONDS = 5 * 60
DEFAULT_WATERING_DURATION = 5 * 60

CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(
CONF_WATERING_DURATION, default=DEFAULT_WATERING_DURATION
): cv.time_period,
vol.Optional(CONF_PACKET_DUMP, default=DEFAULT_PACKET_DUMP): cv.boolean,
vol.Optional(CONF_CONF_DIR, default=DEFAULT_CONF_DIR): cv.string,
}
)
},
Expand All @@ -50,11 +68,24 @@ async def async_setup(hass, config):
return True

conf = config[DOMAIN]
packet_dump = conf.get(CONF_PACKET_DUMP)
conf_dir = conf.get(CONF_CONF_DIR)

_LOGGER.info("config dir %s", hass.config.config_dir)
if conf_dir == "":
conf_dir = hass.config.config_dir + "/.bhyve"

session = aiohttp_client.async_get_clientsession(hass)

try:
bhyve = BHyve(hass, Client(conf[CONF_USERNAME], conf[CONF_PASSWORD], session,),)
client = Client(conf[CONF_USERNAME], conf[CONF_PASSWORD], session)
bhyve = BHyve(
hass,
client,
storage_dir=conf_dir,
packet_dump=packet_dump,
watering_duration=conf[CONF_WATERING_DURATION],
)
await bhyve.login()
await bhyve.client.api.devices
hass.loop.create_task(bhyve.ws_connect())
Expand All @@ -71,18 +102,29 @@ async def async_setup(hass, config):


class BHyve:
"""Define a class to handle the BHyve websocket."""
"""Define a class to handle the Ambient websocket."""

def __init__(self, hass, client):
def __init__(self, hass, client, *, storage_dir, packet_dump):
"""Initialize."""
self._entry_setup_complete = False
self._hass = hass
self._watchdog_listener = None
self._ws_reconnect_delay = DEFAULT_SOCKET_MIN_RETRY
self._storage_dir = storage_dir
self._packet_dump = packet_dump
self._dump_file = self._storage_dir + "/" + "packets.dump"

self.client: Client = client
self.monitored_conditions = []
self.devices = {}

# Create storage/scratch directory.
try:
os.mkdir(self._storage_dir)
except Exception as err:
_LOGGER.info("Could not create storage dir: %s", err)
pass

async def login(self):
"""Login."""
await self.client.api.login()
Expand Down Expand Up @@ -118,11 +160,15 @@ def on_connect():

def on_message(data):
"""Define a handler to fire when the data is received."""
_LOGGER.debug("New data received: {} - {}".format(data["event"], data["device_id"]))
# _LOGGER.debug("New data received: {} - {}".format(data["event"], data["device_id"]))
# device_id = data.device_id
# self.devices[device_id][ATTR_LAST_DATA] = data
# async_dispatcher_send(self._hass, TOPIC_UPDATE)

if self._packet_dump:
with open(self._dump_file, "a") as dump:
dump.write(pprint.pformat(data, indent=2) + "\n")

_LOGGER.debug("Resetting watchdog")
self._watchdog_listener()
self._watchdog_listener = async_call_later(
Expand Down
6 changes: 5 additions & 1 deletion custom_components/bhyve/const.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
"""Define constants for the BHyve component."""
DOMAIN = "bhyve"
CONF_ATTRIBUTION = "Data provided by api.orbitbhyve.com"
MANUFACTURER = "Orbit BHyve"

CONF_ATTRIBUTION = "Data provided by api.orbitbhyve.com"
CONF_CONF_DIR = ""
CONF_PACKET_DUMP = "packet_dump"
CONF_WATERING_DURATION = 300

ATTR_LAST_DATA = "last_data"

TOPIC_UPDATE = "update"
Expand Down
8 changes: 3 additions & 5 deletions custom_components/bhyve/pybhyve/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,9 @@ async def connect(self) -> None:
try:
self._websocket = await self._session.ws_connect(WS_HOST)

await self.send({
'event': 'app_connection',
'orbit_session_token': self._token
})
await self.send(
{"event": "app_connection", "orbit_session_token": self._token}
)

if self._async_user_connect_handler:
await self._async_user_connect_handler() # type: ignore
Expand Down Expand Up @@ -86,4 +85,3 @@ async def _ping(self) -> None:
"""Ping the websocket."""
_LOGGER.info("Ping")
await self.send({"event": "ping"})

6 changes: 2 additions & 4 deletions custom_components/bhyve/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,7 @@ class BHyveSensor(BHyveEntity):

def __init__(self, bhyve, device, name, icon, unit, update_callback, device_class):
"""Initialize the sensor."""
super().__init__(
bhyve, device, name, icon, update_callback, device_class
)
super().__init__(bhyve, device, name, icon, update_callback, device_class)

self._unit = unit

Expand All @@ -79,7 +77,7 @@ def state(self):

@property
def unit_of_measurement(self):
"""Returns the unit of measurement for the sensor."""
"""Return the unit of measurement for the sensor."""
return self._unit

@property
Expand Down

0 comments on commit 500c24c

Please sign in to comment.