Skeem

CellarTracker __init__.py

Feb 27th, 2021 (edited)
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.61 KB | None | 0 0
  1. # replace "__init__.py" from https://github.com/ahoernecke/ha_cellar_tracker to import all bottles in Home Assistant
  2.  
  3. from cellartracker import cellartracker
  4. import pandas as pd
  5. import numpy as np
  6. import logging
  7.  
  8. from random import seed
  9. from random import randint
  10. from datetime import timedelta
  11.  
  12. from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
  13. import voluptuous as vol
  14. import homeassistant.helpers.config_validation as cv
  15. from homeassistant.util import Throttle
  16.  
  17.  
  18. """Example Load Platform integration."""
  19. DOMAIN = 'cellar_tracker'
  20.  
  21. SCAN_INTERVAL = timedelta(seconds=3600)
  22.  
  23. MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=3600)
  24.  
  25. _LOGGER = logging.getLogger(__name__)
  26.  
  27. CONFIG_SCHEMA = vol.Schema(
  28.     {
  29.         DOMAIN: vol.Schema(
  30.             {
  31.                 vol.Required(CONF_USERNAME): cv.string,
  32.                 vol.Required(CONF_PASSWORD): cv.string,
  33.             }
  34.         )
  35.     },
  36.     extra=vol.ALLOW_EXTRA,
  37. )
  38.  
  39.  
  40. def setup(hass, config):
  41.     """Your controller/hub specific code."""
  42.     # Data that you want to share with your platforms
  43.    
  44.     conf = config[DOMAIN]
  45.    
  46.     username = conf[CONF_USERNAME]
  47.     password = conf[CONF_PASSWORD]
  48.    
  49.     hass.data[DOMAIN] = WineCellarData(username, password)
  50.     hass.data[DOMAIN].update()
  51.    
  52.     hass.helpers.discovery.load_platform('sensor', DOMAIN, {}, config)
  53.    
  54.     return True
  55.  
  56. class WineCellarData:
  57.     """Get the latest data and update the states."""
  58.  
  59.     def __init__(self, username, password):
  60.         """Init the Canary data object."""
  61.  
  62.         # self._api = Api(username, password, timeout)
  63.  
  64.         # self._locations_by_id = {}
  65.         # self._readings_by_device_id = {}
  66.         self._username = username
  67.         self._password = password
  68.        
  69.  
  70.     def get_reading(self, key):
  71.       return self._data[key]
  72.  
  73.     def get_readings(self):
  74.       return self._data
  75.  
  76.     @Throttle(MIN_TIME_BETWEEN_UPDATES)
  77.     def update(self, **kwargs):
  78.         data = {}
  79.         username = self._username
  80.         password = self._password
  81.  
  82.  
  83.         client = cellartracker.CellarTracker(username, password)
  84.        
  85.         list = client.get_inventory()
  86.         df = pd.DataFrame(list)
  87.         df[["Price", "Valuation"]] = df[["Price", "Valuation"]].apply(pd.to_numeric)
  88.        
  89.         groups = ['Varietal', 'Country', 'Vintage', 'Producer', 'Type']
  90.        
  91.         for group in groups:
  92.             group_data = df.groupby(group).agg({'iWine': 'count', 'Valuation': ['sum', 'mean']})
  93.             group_data.columns = group_data.columns.droplevel(0)
  94.             group_data["%"] = 1
  95.             group_data["%"] = (group_data['count'] / group_data['count'].sum()) * 100
  96.             group_data.columns = ["count", "value_total", "value_avg", "%"]
  97.             data[group] = {}
  98.             for row, item in group_data.iterrows():
  99.                 data[group][row] = item.to_dict()
  100.                 data[group][row]["sub_type"] = row
  101.        
  102.         data["total_bottles"] = len(df)
  103.         data["total_value"] = df['Valuation'].sum()
  104.         data["average_value"] = df['Valuation'].mean()
  105.        
  106.         list = client.get_list()
  107.         df = pd.DataFrame(list)
  108.  
  109.         #columns = ["Quantity", "Type", "Country", "Region", "Vintage", "Varietal", "Wine", "BeginConsume", "EndConsume", "CT", "Size", "Price"]  # define columns
  110.         columns = ["Quantity", "Type", "Country", "Region", "Vintage", "Varietal", "Wine", "BeginConsume", "EndConsume", "CT", "Size", "Price", "Location", "Bin"] #define columns
  111.         group_data = df.reindex(columns=columns)  # get columns
  112.         group_data[["Quantity"]] = group_data[["Quantity"]].apply(pd.to_numeric)  # make Quantity a numeric value
  113.         #group_data.columns = ['count', 'type', 'country', "region", "vintage", "varietal", "wine", "beginconsume", "endconsume", "score", "size", "price"]  # rename columns
  114.         group_data.columns = ['count', 'type', 'country', "region", "vintage", "varietal", "wine", "beginconsume", "endconsume", "score", "size", "price", "location", "bin"] #rename columns
  115.         group_data.index = df['iWine']  # create index (unique name)
  116.  
  117.         group = 'Flaske'  # Add additional data to dict
  118.         data[group] = {}
  119.         for row, item in group_data.iterrows():
  120.             data[group][row] = item.to_dict()
  121.             data[group][row]["sub_type"] = row
  122.         self._data = data
  123.  
  124.  
  125.  
  126. #Two types of export/import are used in this integration. Headers can be found here:
  127. #https://www.cellartracker.com/xlquery.asp?Table=Inventory
  128. #https://www.cellartracker.com/xlquery.asp?Table=list
  129. #see also https://support.cellartracker.com/article/29-exporting-data    
Add Comment
Please, Sign In to add comment