from utime import sleep, sleep_ms
from hcsr04 import HCSR04
from machine import Pin, Signal, ADC, Timer
import network, time
import ujson
from umqtt.simple import MQTTClient

MQTT_CLIENT_ID = "VitalScan"
MQTT_BROKER    = "test.mosquitto.org"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "empresa/scan"

adc = ADC(34)
led = Signal(Pin(2, Pin.OUT), invert=True)
distancia = HCSR04(trigger_pin=13, echo_pin=12)
sensor = ADC(Pin(32))

m = 0.001  # factor de conversión
offset = 1000
MAX_HISTORY = 250

# Maintain a log of previous values to
# determine min, max and threshold.
history = []
beat = False
beats = 0

def adc_to_kg(adc_value):
    """Convierte el valor del ADC a kilogramos según la calibración."""
    kg = m * (adc_value - offset)
    return max(0, kg) 

def calculate_bpm(t):
    global beats
    print('BPM:', beats * 6)  # Calculate BPM as beats per minute
    beats = 0  # Reset the beat counter

def conectaWifi(red, password):
    global miRed
    miRed = network.WLAN(network.STA_IF)     
    if not miRed.isconnected():              #Si no está conectado…
        miRed.active(True)                   #activa la interface
        miRed.connect(red, password)         #Intenta conectar con la red
        print('Conectando a la red', red +"…")
        timeout = time.time ()
        while not miRed.isconnected():           #Mientras no se conecte..
            if (time.ticks_diff (time.time (), timeout) > 10):
                return False
    return True

if conectaWifi("Wokwi-GUEST", ""):
    print ("Conexión exitosa!")
    print('Datos de la red (IP/netmask/gw/DNS):', miRed.ifconfig())

    print("Conectando a  MQTT server... ",MQTT_BROKER,"...", end="")
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
    client.connect()

    timer = Timer(1)
    timer.init(period=10000, mode=Timer.PERIODIC, callback=calculate_bpm)

    while True:
        try:
            distance = distancia.distance_cm()
            dato = sensor.read_u16()
            peso = adc_to_kg(dato)
            v = adc.read()
            history.append(v)
            # Get the tail, up to MAX_HISTORY length
            history = history[-MAX_HISTORY:]
            minima, maxima = min(history), max(history)
            threshold_on = (minima + maxima * 3) // 4   # 3/4
            threshold_off = (minima + maxima) // 2      # 1/2

            if not beat and v > threshold_on:
                beat = True
                beats += 1
                led.on()

            if beat and v < threshold_off:
                beat = False
                led.off()

            print("Distancia: {:.1f} cm, Peso: {:.2f} kg, BPM:{}".format(distance, peso, beats))
            sleep(1)
            
            message = ujson.dumps({
                "Estatura":distance,
                "Peso":peso,
                "BPM":beats,
                })

            print("Reportando a  MQTT topic {}: {}".format(MQTT_TOPIC, message))
            client.publish(MQTT_TOPIC, message)
        except Exception as e:
            print("Error:", str(e))
            client.disconnect()
            break

else:
    print ("Imposible conectar")
    miRed.active (False)
    
$abcdeabcde151015202530354045505560fghijfghij
$abcdeabcde151015202530354045505560fghijfghij