CCCPaste

influxdb_query_trend

#!/usr/bin/env python

from influxdb import InfluxDBClient
import datetime
import numpy as np
import pandas as pd

@service
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):

    log.debug('received parameters: ' + str(locals()))

    if database is None:
        log.error('"database" is required but not passed on service call to influxdb_query')
        return

    if query is None:
        log.error('"query" is required but not passed on service call to influxdb_query')
        return

    if entity_id is None:
        log.error('"entity_id" is required but not passed on service call to influxdb_query')
        return

    # Connect to InfluxDB
    influxdbclient = InfluxDBClient(
						host=get_config('host'),
						port=get_config('port'),
						username=get_config('username'),
        				password=get_config('password'),
        				database=database
    					)

    # Query to InfluxDB
    try:
        response = task.executor(influxdbclient.query, query)
    except:
        log.error('exception when processing parameters: ' + str(locals()))
        raise

    log.info('query result: ' + str(response))

    # Get the data from the query
    points = response.get_points()    
    
    def import_state(points):
        df = pd.DataFrame(points)
        df['mean'] = df['mean'].apply(lambda x: float(x))    
        x = np.arange(df['time'].size)   
        fit = np.polyfit(x,df['mean'],deg=1)
        return fit[0]

    lastPoint = import_state(points)
    
    attributes = {}

    # Set the entity_id attributes
    if unit_of_measurement:
        attributes['unit_of_measurement'] = unit_of_measurement
    if friendly_name:    
        attributes['friendly_name'] = friendly_name
    if icon:    
        attributes['icon'] = icon
        
    attributes.update({'m': lastPoint})
    log.info(f"Attributes : {attributes}")    
    
    # Create entity and return the state 
    if lastPoint > 0:
        state.set(entity_id, value=1, new_attributes=attributes)
    elif lastPoint < 0:
        state.set(entity_id, value=-1, new_attributes=attributes)
    
    log.info(f"Entity state value: {state.get(entity_id)}")

# InfluxDB credentials
def get_config(name):    
    if name == 'host':
        value = 'a0d7b954-influxdb'
        return value    
    elif name == 'port':
        value = '8086'
        return value
    elif name == 'username':
        value = 'homeassistant'
        return value
    elif name == 'password':
        value = 'homeassistant'
        return value

# Pyscript startup and app reload
@time_trigger('startup')
def load():
    log.info(f'app has started')

    # Check required configuration
    get_config('host')
    get_config('port')
    get_config('username')
    get_config('password')