106 lines
2.7 KiB
Python
Executable File
106 lines
2.7 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
import time
|
|
from datetime import datetime, timezone
|
|
from pymodbus.client import ModbusTcpClient
|
|
|
|
|
|
WISE_IP = "10.43.54.249"
|
|
WISE_PORT = 502
|
|
WISE_UNIT = 1
|
|
|
|
POLL_INTERVAL_S = 0.02
|
|
DEBOUNCE_S = 0.02
|
|
|
|
|
|
def utc_now():
|
|
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
|
|
|
|
def read_di(client):
|
|
rr = client.read_discrete_inputs(
|
|
address=0,
|
|
count=2,
|
|
device_id=WISE_UNIT,
|
|
)
|
|
|
|
if rr.isError():
|
|
raise RuntimeError(f"Error leyendo DI: {rr}")
|
|
|
|
di0 = bool(rr.bits[0])
|
|
di1 = bool(rr.bits[1])
|
|
|
|
return di0, di1
|
|
|
|
|
|
def main():
|
|
client = ModbusTcpClient(WISE_IP, port=WISE_PORT, timeout=1)
|
|
|
|
if not client.connect():
|
|
raise RuntimeError(f"No conecta con WISE {WISE_IP}:{WISE_PORT}")
|
|
|
|
print(f"Conectado a WISE {WISE_IP}:{WISE_PORT}")
|
|
print("DI0 = marcha / automático")
|
|
print("DI1 = pulso sellador")
|
|
print("Prueba: empieza con DI1 abierto, pulsa y suelta claramente.\n")
|
|
|
|
last_di0 = None
|
|
last_di1 = None
|
|
last_rising_ts = 0.0
|
|
count = 0
|
|
|
|
loops = 0
|
|
stats_start = time.perf_counter()
|
|
max_loop_s = 0.0
|
|
|
|
try:
|
|
while True:
|
|
loop_start = time.perf_counter()
|
|
now = loop_start
|
|
|
|
di0, di1 = read_di(client)
|
|
|
|
if last_di0 is None:
|
|
last_di0 = di0
|
|
last_di1 = di1
|
|
print(f"{utc_now()} INIT DI0={int(di0)} DI1={int(di1)}")
|
|
|
|
if di0 != last_di0:
|
|
print(f"{utc_now()} CHANGE DI0 {int(last_di0)} -> {int(di0)}")
|
|
last_di0 = di0
|
|
|
|
if di1 != last_di1:
|
|
print(f"{utc_now()} CHANGE DI1 {int(last_di1)} -> {int(di1)}")
|
|
|
|
if di1 and not last_di1:
|
|
if (now - last_rising_ts) >= DEBOUNCE_S:
|
|
count += 1
|
|
last_rising_ts = now
|
|
print(f"{utc_now()} RISING DI1 count={count}")
|
|
|
|
last_di1 = di1
|
|
|
|
loops += 1
|
|
loop_s = time.perf_counter() - loop_start
|
|
max_loop_s = max(max_loop_s, loop_s)
|
|
|
|
if time.perf_counter() - stats_start >= 5.0:
|
|
elapsed = time.perf_counter() - stats_start
|
|
hz = loops / elapsed
|
|
print(f"{utc_now()} STATS poll_hz={hz:.1f} max_loop_ms={max_loop_s * 1000:.1f} count={count}")
|
|
loops = 0
|
|
stats_start = time.perf_counter()
|
|
max_loop_s = 0.0
|
|
|
|
sleep_s = max(0.0, POLL_INTERVAL_S - loop_s)
|
|
time.sleep(sleep_s)
|
|
|
|
except KeyboardInterrupt:
|
|
print(f"\nParado. Conteo final DI1={count}")
|
|
|
|
finally:
|
|
client.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|