import tinytuya
import requests
import time

def get_value_safely(data, key):
    try:
        # Tente d'obtenir la valeur associée à la clé, si elle existe
        value = data['dps'].get(key, None)

        # Si la valeur est None, renvoie 0
        return value if value is not None else 0

    except Exception as e:
        # En cas d'erreur, imprime un message d'erreur et renvoie 0
        print(f"Erreur : {e}")
        return 0

# Connect to Device
    #"apiKey": "hgkvdyrstyhqudku3xdu",
    #"apiSecret": "704a1bad394a4efe805f46fb04c46916",
    #"apiRegion": "eu-w",
    #"apiDeviceID": "bf4d021ef10d39ea17gpwo"

response = ""
while True:    
    d = tinytuya.OutletDevice(
        dev_id='bf4d021ef10d39ea17gpwo',
        address='192.168.1.15',      # 53 Or set to 'Auto' to auto-discover IP address
        local_key='4.p}ZHi*hO>wVFl-', 
        version=3.5)

    # Get Status
    data = d.status() 
    print('set_status() result %r' % data)

    #data = json.loads(data)

    # Utilisation de la fonction get_value_safely pour remplacer les lignes existantes
    value_105 = get_value_safely(data, '105')
    value_106 = get_value_safely(data, '106')
    value_107 = get_value_safely(data, '107')
    value_108 = get_value_safely(data, '108') or 0
    value_109 = get_value_safely(data, '109') or 0
    value_115 = get_value_safely(data, '115')
    value_116 = get_value_safely(data, '116')
    value_117 = get_value_safely(data, '117')
    value_118 = get_value_safely(data, '118') or 0
    value_119 = get_value_safely(data, '119') or 0

    # Afficher les valeurs
    print("=================================")
    #print("103             :", data['dps'].get('103', None) or 0)
    #print("104             :", data['dps'].get('104', None) or 0)
    print("105 Valeur watt :", value_105 / 10)
    print("106 Valeur mA   :", value_106)
    print("107 Valeur Volt :", value_107 / 10)
    print("108 Cumul  kWh  :", value_108 / 1000)
    print("109 Valeur kWh  :", value_109 / 1000)
    #print("110             :", data['dps'].get('110', None))
    #print("111 Alerte 1    :", data['dps'].get('111', None))
    print("=================================")
    #print("113             :", data['dps'].get('113', None))
    #print("114             :", data['dps'].get('114', None))
    print("115 Valeur watt :", value_115 / 10)
    print("116 Valeur mA   :", value_116)
    print("117 Valeur Volt :", value_117 / 10)
    print("118 Cumul  kWh  :", value_118 / 1000)
    print("119 Valeur kWh  :", value_119 / 1000)
    #print("120             :", data['dps'].get('120', None))
    #print("121 Alerte 2    :", data['dps'].get('121', None))
    print("=================================")

    #print("122             :", data['dps'].get('122', None))
    #print("123             :", data['dps'].get('123', None))
    #print("124             :", data['dps'].get('124', None))
    # Turn On
    #d.turn_on()

    # id domoticz 1181
    # print('1121|0|' + str(value_105) + ";0;" + str(value_115) + ";0;" + str(value_108) + ";" + str(value_118))

    # Effectuer une requête GET
    #url = "http://192.168.1.3:81/json.htm?type=command&param=udevice&idx=1181&nvalue=0&svalue=" + str(value_109) + ";" + str(value_105 / 10) + ";" + str(value_119) + ";" + str(value_115 / 10) + ";;" 
    url = "http://192.168.1.3:81/json.htm?type=command&param=udevice&idx=1181&nvalue=0&svalue=" + str(value_109) + ";0;" + str(value_119) + ";0;" + str(value_105 / 10) + ";" + str(value_115 / 10) #USAGE1;USAGE2;RETURN1;RETURN2;CONS;PROD

    #USAGE1;USAGE2;RETURN1;RETURN2;CONS;PROD 
    print(url)
    try:
        response = requests.get(url)
        print(response)
    except requests.RequestException as e:
        # Gérez les autres erreurs liées aux requêtes ici
        print(f"Erreur de requête : {e}")
    
    time.sleep(1)


    # 1185 Radiateur 
    idx = "1185"     
    url = "http://192.168.1.3:81/json.htm?type=command&param=udevice&idx=" + idx + "&svalue=" + str(value_115 / 10) + ";0&nvalue=0";
    try:
        response = requests.get(url)
        print(response)
    except requests.RequestException as e:
        # Gérez les autres erreurs liées aux requêtes ici
        print(f"Erreur de requête : {e}")
    print(response)    
    time.sleep(1)

    # 1184 Chauffe eau 2
    idx = "1184"     
    url = "http://192.168.1.3:81/json.htm?type=command&param=udevice&idx=" + idx + "&svalue=" + str(value_105 / 10) + ";0&nvalue=0";
    try:
        response = requests.get(url)
        print(response)
    except requests.RequestException as e:
        # Gérez les autres erreurs liées aux requêtes ici
        print(f"Erreur de requête : {e}")
    
    #                --USAGE1= energy usage meter tariff 1, This is an incrementing counter
    #                --USAGE2= energy usage meter tariff 2, This is an incrementing counter
    #                --RETURN1= energy return meter tariff 1, This is an incrementing counter
    #                --RETURN2= energy return meter tariff 2, This is an incrementing counter
    #                --CONS= actual usage power (Watt)
    #                --PROD= actual return power (Watt)
    #                .. tostring(math.floor(watt_p1)) .. ';'
    #                .. tostring(math.floor(watt_p2)) .. ';'
    #                --  + value_solar2 - counter_solar2
    #                .. tostring(math.floor(value_solar - counter_solar + value_solar2 - counter_solar2)) .. ';'
    #                .. '0;'
    #                .. tostring(math.floor(math.max(0,watt) + watt_solaire)).. ';'
    #                .. tostring(math.floor(watt_solaire)) --math.floor(ConsumoEnergyBalance / 1000)) --round(watt,0))


    # Turn Off
    #d.turn_off()
    time.sleep(25)


