import time
import random
from influxdb import InfluxDBClient
client = InfluxDBClient(host="localhost", port=8086, username="influxdb", password="influxdbTSGAMES")
client.create_database("influxdb")
client.switch_database('influxdb')
#!/usr/bin/env python3

import argparse
import signal
import sys
import time
import logging

from rpi_rf import RFDevice
VOLTAGE = 0
AMPERE = 1

# min samples in a row stable to be accepted as new value
STABLE_COUNT = 3
# max diff which is considered stable between new values
STABLE_DIFF_THRESHOLD = .1
rfdevice = None

# pylint: disable=unused-argument
def exithandler(signal, frame):
    rfdevice.cleanup()
    sys.exit(0)

logging.basicConfig(level=logging.INFO)

parser = argparse.ArgumentParser(description='Receives a decimal code via a 433/315MHz GPIO device')
parser.add_argument('-g', dest='gpio', type=int, default=27,
                    help="GPIO pin (Default: 27)")
args = parser.parse_args()

signal.signal(signal.SIGINT, exithandler)
rfdevice = RFDevice(args.gpio, rx_tolerance=80)
rfdevice.enable_rx()
timestamp = None
logging.info("Listening for codes on GPIO " + str(args.gpio))
previous_values = {}
counts = {}
while True:
    if rfdevice.rx_code_timestamp != timestamp:
        timestamp = rfdevice.rx_code_timestamp
        code = rfdevice.rx_code
        codeType = code & 0xff
        value = (code >> 8) / 1000.
        U = 0
        I = 0
        if value:
            if codeType in previous_values and abs(previous_values[codeType]-value) <= STABLE_DIFF_THRESHOLD:
                counts[codeType] += 1
            else:
                counts[codeType] = 0
            previous_values[codeType] = value
        logging.info("Data Received: " + str(code) + "/" + str(codeType) + " / " + str(value))
        if codeType in counts and counts[codeType] >= STABLE_COUNT:
            if codeType == VOLTAGE or True:
                U = value
                logging.info("Stable Voltage:" +str(U))
                client.write_points([
                    {
                        "measurement": "solar",
                        "tags": {
                            "type": "U"
                        },
                        "fields": {
                            "value": U
                        }
                    }
                ], time_precision='ms')
            if codeType == AMPERE:
                logging.info("Ampere")
                I = value
            
    time.sleep(0.05)
rfdevice.cleanup()