from opcua import Client
from influxdb import InfluxDBClient
import time


url = "opc.tcp://192.168.0.10:4840"
#url = "opc.tcp://172.16.24.144:4840"
client = Client(url)

client.connect()
print("Cliente Conectado al Servidor")

while True:
    Temp = client.get_node("ns = 2;i = 2")
    Temperature = Temp.get_value()
    Presion = client.get_node("ns = 2;i = 3")
    Presion2 = Presion.get_value()
    Time = client.get_node("ns = 2;i = 4")
    Tiempo = Time.get_value()
    c = str(Tiempo)
    tiempodb = tiempodb = c[0:10]+"T"+c[11:13]+":"+c[14:16]+":"+c[17:19]+"Z"
    print("Temperatura = {0} Presión = {1}  Tiempo {2}".format(
        Temperature, Presion2, Tiempo))
    json_body = [
        {   "measurement": "Tempe",
            "tags": {
            "host": "raspberry"  # OPC-SERVER
         },
            "time":  tiempodb,  
            "fields": {
            "value": float(Temperature)
         }
         }
    ]
    json_body2 = [
        {"measurement": "pres",
         "tags": {
             "host": "raspberry"  # OPC-SERVER
         },
            "time":  tiempodb,  
            "fields": {
            "value": float(Presion2)
         }
         }

    ]

    clientDB = InfluxDBClient('127.0.0.1')
    clientDB.switch_database('wheater_station')
    clientDB.write_points(json_body)
    clientDB.write_points(json_body2)
    time.sleep(1)
#print("Temperatura = {0} Presión = {1} Humedad = {2}% Tiempo {3}".format(Temperature, Presion2, Humedad, Tiempo))
