Advertisement
jarekmor

influxdb_query_trend

Sep 18th, 2022
667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.90 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. from influxdb import InfluxDBClient
  4. import datetime
  5. import numpy as np
  6. import pandas as pd
  7.  
  8. @service
  9. def influxdb_query(database=None, query=None, key_field_name='time', value_field_name=None, entity_id=None, unit_of_measurement=None, friendly_name=None, icon=None):
  10.  
  11.     log.debug('received parameters: ' + str(locals()))
  12.  
  13.     if database is None:
  14.         log.error('"database" is required but not passed on service call to influxdb_query')
  15.         return
  16.  
  17.     if query is None:
  18.         log.error('"query" is required but not passed on service call to influxdb_query')
  19.         return
  20.  
  21.     if entity_id is None:
  22.         log.error('"entity_id" is required but not passed on service call to influxdb_query')
  23.         return
  24.  
  25.     # Connect to InfluxDB
  26.     influxdbclient = InfluxDBClient(
  27.                         host=get_config('host'),
  28.                         port=get_config('port'),
  29.                         username=get_config('username'),
  30.                         password=get_config('password'),
  31.                         database=database
  32.                         )
  33.  
  34.     # Query to InfluxDB
  35.     try:
  36.         response = task.executor(influxdbclient.query, query)
  37.     except:
  38.         log.error('exception when processing parameters: ' + str(locals()))
  39.         raise
  40.  
  41.     log.info('query result: ' + str(response))
  42.  
  43.     # Get the data from the query
  44.     points = response.get_points()    
  45.    
  46.     def import_state(points):
  47.         df = pd.DataFrame(points)
  48.         df['mean'] = df['mean'].apply(lambda x: float(x))    
  49.         x = np.arange(df['time'].size)  
  50.         fit = np.polyfit(x,df['mean'],deg=1)
  51.         return fit[0]
  52.  
  53.     lastPoint = import_state(points)
  54.    
  55.     attributes = {}
  56.  
  57.     # Set the entity_id attributes
  58.     if unit_of_measurement:
  59.         attributes['unit_of_measurement'] = unit_of_measurement
  60.     if friendly_name:    
  61.         attributes['friendly_name'] = friendly_name
  62.     if icon:    
  63.         attributes['icon'] = icon
  64.        
  65.     attributes.update({'m': lastPoint})
  66.     log.info(f"Attributes : {attributes}")    
  67.    
  68.     # Create entity and return the state
  69.     if lastPoint > 0:
  70.         state.set(entity_id, value=1, new_attributes=attributes)
  71.     elif lastPoint < 0:
  72.         state.set(entity_id, value=-1, new_attributes=attributes)
  73.    
  74.     log.info(f"Entity state value: {state.get(entity_id)}")
  75.  
  76. # InfluxDB credentials
  77. def get_config(name):    
  78.     if name == 'host':
  79.         value = 'a0d7b954-influxdb'
  80.         return value    
  81.     elif name == 'port':
  82.         value = '8086'
  83.         return value
  84.     elif name == 'username':
  85.         value = 'homeassistant'
  86.         return value
  87.     elif name == 'password':
  88.         value = 'homeassistant'
  89.         return value
  90.  
  91. # Pyscript startup and app reload
  92. @time_trigger('startup')
  93. def load():
  94.     log.info(f'app has started')
  95.  
  96.     # Check required configuration
  97.     get_config('host')
  98.     get_config('port')
  99.     get_config('username')
  100.     get_config('password')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement