from flask import Flask, request
import tinytuya

app = Flask(__name__)

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

@app.route('/control', methods=['POST'])
def control_device():
    action = request.json.get('action')
    device_id = 'bf9109f5435d9bb3c6avlr'
    local_key = '/Pht&M$(/nt@t}qV'
    ip_address = '192.168.1.14'
    
    d = tinytuya.OutletDevice(dev_id=device_id, address=ip_address, local_key=local_key, version=3.4)
    d.set_version(3.4)  # Set the version of Tuya protocol
    
#    if action == 'on':
#        d.turn_on()
#    elif action == 'off':
#        d.turn_off()
    data = d.status() 
    print('set_status() result %r' % data)

    #data = json.loads(data)
 #   for key, value in data['dps'].items():
 #       print(f'{key.ljust(5)}: {str(value).ljust(10)}')


    # Extraire les valeurs des champs spécifiques
    #total     = data['dps'].get('115', None) / 10
    # Utilisation de la fonction get_value_safely pour remplacer les lignes existantes
    total_1   = get_value_safely(data, '1')
    total_2   = get_value_safely(data, '2')
    volt_1    = get_value_safely(data, '112') / 10 or 0
    freq_1    = get_value_safely(data, '111') / 100 or 0
    current_1 = get_value_safely(data, '113') or 0
    factor_1  = get_value_safely(data, '110') / 100 or 0
    prod_1    = get_value_safely(data, '107') or 0

    watt_1    = get_value_safely(data, '101') / 10 or 0
    watt_2    = get_value_safely(data, '105') / 10 or 0
    prod_2    = get_value_safely(data, '108') or 0
    current_2 = get_value_safely(data, '114') or 0
    sens_1    = get_value_safely(data, '102')
    sens_2    = get_value_safely(data, '104')

    value_106 = get_value_safely(data, '106') or 0
    value_109 = get_value_safely(data, '109') or 0

   
    return {"conso_apparente": (watt_1 if sens_1 == "FORWARD" else - watt_1), "production": watt_2 if watt_2 > 0  else 0 }

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

