'''
  ____   ___  _   _ _   _ ____
 / ___| / _ \| | | | \ | |  _ \
 \___ \| | | | | | |  \| | | | |
  ___) | |_| | |_| | |\  | |_| |
 |____/ \___/ \___/|_| \_|____/

python3 /var/www/nebuleair_pro_4g/sound_meter/read.py

Read current values from NSRT MK4 Sound Level Meter (USB /dev/ttyACM0)
Used by the web interface "Get Data" button via launcher.php
'''

import json
import nsrt_mk3_dev

try:
    nsrt = nsrt_mk3_dev.NsrtMk3Dev('/dev/ttyACM0')

    leq_level = nsrt.read_leq()
    weighted_level = nsrt.read_level()
    weighting = nsrt.read_weighting()
    time_constant = nsrt.read_tau()

    data = {
        "LEQ": round(leq_level, 2),
        "dBA": round(weighted_level, 2),
        "weighting": str(weighting),
        "tau": time_constant
    }
    print(json.dumps(data))

except Exception as e:
    err_msg = str(e)
    if "No such file or directory" in err_msg or "could not open port" in err_msg:
        print(json.dumps({"error": "Capteur déconnecté — vérifiez le câblage USB du sonomètre NSRT MK4 (/dev/ttyACM0)", "disconnected": True}))
    elif "Permission denied" in err_msg:
        print(json.dumps({"error": "Permission refusée sur /dev/ttyACM0 — exécutez: sudo chmod 777 /dev/ttyACM0", "disconnected": False}))
    else:
        print(json.dumps({"error": err_msg}))
